-1

I'm making a Pokedex site just for practice and to learn how to properly use API Rest, but I've been having some issues, when you first enter the site the API is called twice for no reason, and when you press the next or previous button you have to press it twice in order to load the prev/next pokemon. I don't understand why it's giving that error.

Link to GitHub: https://github.com/Makita7/pokedex Here is the code were I called the API:

    export const CardList = () =>{
    const [ pokeInfo, setPokemonInfo ] = useState([]);
    const [ loading, setLoading ] = useState();
    const [ url, setUrl ] = useState('https://pokeapi.co/api/v2/pokemon');
    const [ nextUrl, setNextUrl ] = useState();
    const [ prevUrl, setPrevtUrl ] = useState();
    const [ pokedex, setPokedex ] = useState();
    //console.log(pokedex)

    const FetchData = async () => {
      //res short for response
      setLoading(true);
      const res = await axios.get(url);
      setNextUrl(res.data.next);
      setPrevtUrl(res.data.previous);
      GetData(res.data.results);
      setLoading(false);
    }

    const GetData = async(res) =>{
      res.map ( async(item) =>{
        const result = await axios.get(item.url)
        //console.log(item.name);

        setPokemonInfo(state =>{
            state = [...state, result.data]
            state.sort(( a, b ) => a.id > b.id ? 1 : -1)
            return state;
        })
      })
    }

    useEffect(() => {
      FetchData();
    }, []);

  return(
    <div className="">
      <MoreInfo data={pokedex}/>

      <div className="cardList flexbox">
        <Card pokemon={pokeInfo} loading={loading} infoPokemon={item=>setPokedex(item)}/>
      </div>
      <div className="btnContainer center">
            <button className="btn" onClick={() =>{
                setLoading(true)
                setPokemonInfo([])
                setUrl(prevUrl)
                FetchData()
                setLoading(false);
          }}>

              Previous
          </button>
          
          <button className="btn"  onClick={() =>{
                setLoading(true)
                setPokemonInfo([])
                setUrl(nextUrl)
                FetchData()
                setLoading(false);
            }}>

                Next
          </button>

      </div>
    </div>
  );
}
S.Marx
  • 977
  • 10
  • 14

1 Answers1

0

Hi I cloned your project and I wasn't able to figure out why you need to press the buttons twice to see the prev/next result but I was able to figure out why it fetches data twice.

The answer came from this stack overflow post

basically you just had to remove the React.Strict that surrounds your App component from the index.js file and it solves the 'double fetching' when you first visit the site.