Я пытаюсь выяснить, как выбрать один элемент из запроса, но я застреваю. У меня есть список элементов (покемонов), но когда я нажимаю на один, я хочу выбрать этот конкретный элемент (покемонов), перезапустить запрос с выбранным элементом, чтобы я мог получить все его детали.
Вот песочница с кодом с примером.
А вот и код:
// graphql queries
import gql from 'graphql-tag'
const GET_ALL_POKEMONS = gql`
{
Pokemons(first: 151) {
id
name
image
types(first: 1) {
name
}
abilities {
name
}
stats {
name
value
}
}
}
`
const GET_POKEMON_DETAILS = gql`
query PokemonDetails($pokemonName: String!) {
Pokemon(name: $pokemonName) {
name
types {
name
}
abilities {
name
}
stats {
name
value
}
}
}
`
export { GET_ALL_POKEMONS, GET_POKEMON_DETAILS
}
// Pokemon Detail view
function PokemonDetails(props): ReactNode {
const { pokemonName } = props.name
// This is the Query I will like to use to get a detail view of my pokemon:
// Having problems hooking it up to the onClick
const { loading, error, data, networkStatus } = useQuery(GET_POKEMON_DETAILS, {
variables: { name: pokemonName },
})
if (loading) return <Paragraph>Loading...</Paragraph>
if (error) return <Paragraph textColor="red">Error: {error.message}</Paragraph>
return <div>{/* Need to put the pokemon details here */}</div>
}
// This gives me a single Pokemon
function PokemonItem(props: PokemonItemProps): ReactNode {
const { pokemon } = props
function onHandleSave() {
console.log(`I was save: ${pokemon.name}`)
}
function onHandleSelect() {
console.log(`I was selected: ${pokemon.name}`)
}
return (
<CardArticle>
<Avatar alt="pokemon-image" src={pokemon.image} />
<Paragraph>ID: {pokemon.id}</Paragraph>
<Paragraph>Name: {pokemon.name}</Paragraph>
{/* [TODO]: Need to either use lodash or a `.map()` for the following data */}
<Paragraph>Type: {pokemon.types.name}</Paragraph>
<Paragraph>Abilities: {pokemon.abilities.name}</Paragraph>
<Paragraph>Stats: {pokemon.stats.name}</Paragraph>
<Button onClick={onHandleSelect}>Select this Pokemon</Button>
<Button onSubmit={onHandleSave}>Save this Pokemon</Button>
</CardArticle>
)
}
// This gives me a list of all my Pokemons
function PokemonList(props: PokemonListProps): ReactNode {
const { loading, error, data } = useQuery(GET_ALL_POKEMONS) // This works
if (loading) return <Paragraph>Loading...</Paragraph>
if (error) return <Paragraph textColor="red">Error: {error.message}</Paragraph>
return (
<CardsSection>
{data.Pokemons.map((pokemon) => (
<PokemonItem key={pokemon.id} pokemon={pokemon} />
))}
</CardsSection>
)
}