Skip to content
Advertisement

Change component state – REACT

I’m currently working on a project with the Pokemon API and i’m facing a problem. I want to change the value parameter in the async function getPokemonTypes(), but the value I receive in handleSelect() is not working. On the console.log(value), the value changes every time I select a different option. Could someone tell me what I’m doing wrong?

JavaScript

Advertisement

Answer

You need to add type to the dependnecies array of useEffect:

JavaScript

Keep in mind this code has some issues, as you might end up seeing data for a type that doesn’t match the one in the URL if something like this happens:

  • You select fire and getPokemonTypes('fire') is called.
  • You select to ice and getPokemonTypes('ice') is called.
  • getPokemonTypes('ice') finishes loading and the rest of the fetchData function executes.
  • getPokemonTypes('fire') finishes loading and the rest of the fetchData function executes.
  • The selected option is now ice but see data from fire.

The proper way to do it would be like this:

JavaScript

Also, you have an error here:

JavaScript

You want to store all those promises in the data array and await them all together with Promise.all below, but you are instead awaiting them one by one. It should be like this:

JavaScript
User contributions licensed under: CC BY-SA
9 People found this is helpful
Advertisement