0

Im new in react development and i dont understand why, in the following code, the useEffect is running two times. Maybe the problem is on await, fetch or async words, but i dont know what to do.

import './App.css';
import Navbar from './Navbar/Navbar';
import { useState, useEffect } from 'react';

function App() {

  const [allPokemons, setAllPokemons] = useState([]);
  const [loadMore, setLoadMore] = useState("https://pokeapi.co/api/v2/pokemon?limit=20");
  
  const getAllPokemons = async () => {
    const res = await fetch(loadMore);
    const data = await res.json();
    console.log(data);
    
    setLoadMore(data.next);
    // setAllPokemons(data);

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

      });
    }
    createPokemonObject(data.results);
  }

  useEffect(() => {
    getAllPokemons();
  }, []);
  
  return (
    <div className="App">
      <Navbar />
      <div className='pokemons'>
        {allPokemons.map((pokemon) => 
          <li>{pokemon.name}</li>
        )}
      </div>
    </div>
  );
}

export default App;

Thomaz
  • 5
  • 1
  • 2
    are you [using React 18 in development mode](https://stackoverflow.com/a/72870534/633183)? – Mulan Aug 20 '22 at 13:18
  • Refer.. https://stackoverflow.com/questions/60618844/react-hooks-useeffect-is-called-twice-even-if-an-empty-array-is-used-as-an-ar – sms Aug 20 '22 at 13:36
  • 2
    Does this answer your question? [React Hooks: useEffect() is called twice even if an empty array is used as an argument](https://stackoverflow.com/questions/60618844/react-hooks-useeffect-is-called-twice-even-if-an-empty-array-is-used-as-an-ar) – Favour Felix Chinemerem Aug 20 '22 at 13:43

0 Answers0