0

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);
    }
   })
 },[])

1 Answer 1

1

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 !!!!
Sign up to request clarification or add additional context in comments.

2 Comments

Hi Mohammad your coding working fine, But how to check that setdataObject(temArray) , is getting all the data?? By using Debug, We can see all the data? because as you said Immediately after changing any state value I will not get the changes Immeditately
you can use useEffect hook to identify any change in the dataObject

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.