Home > Blockchain >  How to avoid unnecessary API calls with useEffect?
How to avoid unnecessary API calls with useEffect?

Time:06-26

I'm still beginner to ReactJS and I'm having trouble rendering a list.

I don't know why, all the time calls are being made to my API. Since I don't put any dependency on useEffect, that is, I should only render my function once.

I don't understand why this is happening. Can you tell me what I'm doing wrong?

Here's my code I put into enter image description here

Thank you very much in advance.

CodePudding user response:

I was just having the same issue in my project the way I solved is by moving the function definition inside the useEffect

     React.useEffect(() => {
             const getAllPokemons = async () => {
             const { data } = await axios.get(`${BASE_URL}/pokemon`);

             data.results.map((pokemon) => getPokeType(pokemon));
         };
      getAllPokemons();
     }, []); 

If this solves your problem please accept the answer.

CodePudding user response:

Your issue is that you are calling setPokemons inside getPokeType (which is called for each data in part). Your useEffect is called just once (as expected) and the ${BASE_URL}/pokemon call is executed just once too. But getPokeType is called 20 times I think in your case and the pokemons state is changed 20 times as well (once for each instance from data.results).

What I would reccomend instead in your case is creating a list of all the pokemons and setting the state just once at the end. So something like:

  ...

  const getPokeType = async (pokemon) => {
    const { data } = await axios.get(pokemon.url);
    return data;
  };
  const getAllPokemons = async () => {
    const { data } = await axios.get(`${BASE_URL}/pokemon`);
    const pokemons = await Promise.all(
      data.results.map((pokemon) => getPokeType(pokemon))
    );
    setPokemons(pokemons);
  };

  React.useEffect(() => {
    getAllPokemons();
  }, []);
  ...
  • Related