1

I'm having an issue with useEffect and useState. I'm trying to fill a state with data from an api, but it results in an infinite loop, even if I use an array with dependencies. It works when I try to get a name. The problem occurs when I try to get an array or an object.

Here the code:

      const id = props.match.params.id;
      const [pokemon, setPokemon] = useState({});
    
      useEffect(() => {
        let cancelRequest;
        axios
      .get(`https://pokeapi.co/api/v2/pokemon/${id}`, {
        cancelToken: new axios.CancelToken(
          (cancel) => (cancelRequest = cancel)
        ),
      })
      .then((res) => {
        setPokemon(res.data);
        console.log(pokemon);
      })
      .catch((err) => {
        console.log(`ERROR:: ${err.message}`);
      });
      return () => {
        cancelRequest();
     };
    }, [id, pokemon]);

Here a sample of data from the console:

{abilities: Array(2), base_experience: 64, forms: Array(1), game_indices: Array(20), height: 7, …}

Thank you.

1
  • 3
    You have pokemon in deps, which means useEffect will be called on every change pokemon. Which happens when you are called setPokemon every useEffect with new ref. Leave only [id] in deps. Commented Jul 13, 2020 at 13:02

1 Answer 1

1

Do not use the axios request inside the useEffect.

Create another function for this and use useCallback. For example:

const fetchPokemon = useCallback(() => {
 axios.get(`https://pokeapi.co/api/v2/pokemon/${id}`)
   .then((res) => {
     setPokemon(res.data);
   })
   .catch(() => {}
}, [id])


useEffect(() => {
 fetchPokemon()
}, [fetchPokemon])

If you pass in pokemon into the dependency array, it will update every single time you call setPokemon since the pokemon update aka, you have an infinte loop.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.