Swr: If useSWR is dependent on state, the return values are undefined

Created on 4 Nov 2019  路  2Comments  路  Source: vercel/swr

const Pokemon = () => {
  const [pokemon, setPokemon] = useState(null);

  const loadPokemon = (url) => setPokemon(url);

  const { data, error } = useSWR('https://pokeapi.co/api/v2/pokemon', fetch);
  const { pokemonData, pokemonError } = useSWR(pokemon, fetch);

  // This is null
  console.log(pokemonData, pokemonError)

  if (error) return <div>failed to load</div>
  if (!data) return <div>loading...</div>

  return <div>{data.results.map(pokemon => {
    return <h2 key={pokemon.name} onClick={() => loadPokemon(pokemon.url)}>{pokemon.name}</h2>
  })}

  </div>
}

Don't know what I am doing wrong. But the second useSWR is always undefined, even though I see the network calls going through.

Most helpful comment

Hello, please try this

const { data: pokemonData, error: pokemonError} = ...

All 2 comments

Hello, please try this

const { data: pokemonData, error: pokemonError} = ...

That works thank you so much

Was this page helpful?
0 / 5 - 0 ratings

Related issues

frdwhite24 picture frdwhite24  路  4Comments

bcomnes picture bcomnes  路  3Comments

Ephys picture Ephys  路  3Comments

oran1248 picture oran1248  路  3Comments

nainardev picture nainardev  路  4Comments