Search code examples
javascriptreactjsrandom

unable to shuffle array correctly in react


I am trying to shuffle an array in react . I fetch the data from the api and then I want to mount the data pictures as a shuffled array in my screen and not in the order I fetched them .

This is my code :

useFetch.js

import {React , useState , useEffect} from 'react';

export default function useFetch() {
  
  const [ pokemon,setPokemon] = useState([]);
  const [shuffled,setShuffled]= useState([]);
  useEffect(()=>{
    const fetchPokemon = async () =>{  //here I fetch my pokemon 
      const promises = [];
      for (let i=1;i<=10;i++){
        let  url = `https://pokeapi.co/api/v2/pokemon/${i}`;
        let response = await fetch(url);
        let result = await response.json();
        promises.push(result);
      }

      const data = await Promise.all(promises);
      setPokemon(...pokemon,data); //successfully sets the pokemon data 
    }


    const shufflePokemon = ()=>{ //here I try to shuffle the pokemon array and return a random on mount 
      fetchPokemon(); 
      let randomArray= pokemon.map((poke,index)=>{ //this is what I am trying to do to shuffle the array  but it is not correct 
         let  j = Math.floor(Math.random() * (index + 1)); 
         let temp = poke[index];
         poke[index] = poke[j];
         poke[j] = temp;
      })
      setShuffled(...shuffled,randomArray);

    }

    shufflePokemon(); //call shuffle on mount 
  },[])
 
   return {shuffled} //returns shuffled array of objects 

}

In my code above in the shufflePokemon function I try to give an idea of what needs to be done but the code is obviously not correct . I would appreciate your help


Solution

  • You can shuffle the array as soon as you get responses from api.

    useEffect(() => {
      const shuffle = (array) => {
        for (var i = array.length - 1; i > 0; i--) {
          var j = Math.floor(Math.random() * (i + 1));
          var temp = array[i];
          array[i] = array[j];
          array[j] = temp;
        }
      };
    
      const fetchPokemon = async () => {
        //here I fetch my pokemon
        const promises = [];
        for (let i = 1; i <= 10; i++) {
          let url = `https://pokeapi.co/api/v2/pokemon/${i}`;
          let response = await fetch(url);
          let result = await response.json();
          promises.push(result);
        }
    
        const data = await Promise.all(promises);
        shuffle(data);
        setPokemon(data);
      };
    
      fetchPokemon();
    }, []);