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.
pokemonin deps, which meansuseEffectwill be called on every changepokemon. Which happens when you are calledsetPokemoneveryuseEffectwith new ref. Leave only[id]in deps.