Home > other >  Why does my react function function iterate twice?
Why does my react function function iterate twice?

Time:02-04

I am currently trying out a project with the PokeAPI. And have used his guide for help. I can't get rid of the problem that the function iterates twice when called in the useEffect.

When I run the following code with the getAllPokemons in the useEffect

const PokeListPage = () => {
  const [layoutToggle, setLayoutToggle] = useState(false);

  const [allPokemons, setAllPokemons] = useState([]);
  const [loadPoke, setLoadPoke] = useState(
    "https://pokeapi.co/api/v2/pokemon?limit=20"
  );

  useEffect(() => {
    getAllPokemons();
    console.log(allPokemons);
  }, []);

  const getAllPokemons = async () => {
    const res = await fetch(loadPoke);
    const data = await res.json();
    setLoadPoke(data.next);

    function createPokemonObject(result) {
      result.forEach(async (pokemon) => {
        const res = await fetch(
          `https://pokeapi.co/api/v2/pokemon/${pokemon.name}`
        );
        const data = await res.json();
        setAllPokemons((currentList) => [...currentList, data]);
      });
    }
    createPokemonObject(data.results);
    console.log(allPokemons);
  };

I get doublets of the first 20 objects in allPokemons. See output:

enter image description here

But when I remove the function and uses a button to trigger the function it behaves as expected. Which means that the function populates the allPokemon array with one object per pokemon. See output.

enter image description here

I have tried everything from copying entire files from other repositories and with an accuracy I didn't knew I had followed different tutorials but the problem remains. Does anyone know why?

CodePudding user response:

It may be bcz you are rendering you app into a React.Strictmode component that runs specific functions and methods twice as a way to help you detect unintnetional side-effect. Since the side-effect is a state update.so, this triggers a rerender.

Use a useEffect to run the effect once when the component mounts.

  • Related