Sundeep
Sundeep

Reputation: 179

How to push Multiple Objects into an array using useState hook

I need to push the Multiple objects in to an array by using UseState hook, Here I am getting the multiple objects into "getallData", So I need to sent the all the multiple objects into setdataObject. But here I am not getting all the multiple objects data and getting an Empty Array..

 const [data, setData] = useState([])
  const [dataObject,setdataObject] = useState([{}])

 useEffect(()=>{
   fetch('http://localhost:3000/results')
   .then(res =>res.json())
   .then((results)=>{
    setData(results);
    //console.log(results);
    for(let i=0;i<results.length;i++){
      //console.log(results);
      const getallData={
        name :`${results[i].name.first} ${results[i].name.last}`,
        money : results[i].price.money.wealth
      }
      //console.log(getallData);
      setdataObject(getallData);
      console.log(dataObject);
    }
   })
 },[])

Upvotes: 0

Views: 2520

Answers (1)

Mohammad Faisal
Mohammad Faisal

Reputation: 2363

You are calling setdataObject inside a loop. Rather you can add the all datas into an array and set it at the end of the loop. Something like this

    const tempArray = []
    for(let i=0;i<results.length;i++){
      const getallData={
        name :`${results[i].name.first} ${results[i].name.last}`,
        money : results[i].price.money.wealth
      }
      tempArray.push(getallData)
    }
    setdataObject(tempArray);

Another thing. As setState functions are asynchronus so if you call console.log() immediately after changing any state value you will not get the changes immediately. As a result your following code is printing wrong output

 setdataObject(getallData);
 console.log(dataObject);    // WRONG !!!!

Upvotes: 1

Related Questions