0

From the API i have fetched the data in the following format

{ teamsregistered: [ { paid: false, _id: 602dea67451db71e71e4babd, name: 'MOH', mobile: '+919566879683', tag: 'JAR1NAH', __v: 0 }, { paid: false, _id: 602deb602924a41fb0c88415, name: 'RAJ', mobile: '+919566879683', tag: 'JAR1NAH', __v: 0 }, { paid: false, _id: 602deb692924a41fb0c88416, name: 'two', mobile: '+919566879683', tag: 'JAR1NAH', __v: 0 } ], rounds: [], table: [], ongoinground: 0, status: 'not completed', totalamount: '0', _id: 602dea4d451db71e71e4babb, name: 'ATD', tag: 'JAR1NAH', date: '2021-02-25T18:30:00.000Z', __v: 0 }

In this teams registered is a array of Objects .i need to store the array of objects in a state hook and need an access to every element in it and also i need send the data to another component,

.then(response => {
        console.log(response.teamsregistered) //it shows correct output
        setData({...data,
            name:response.name,
            date:response.date,
            ongoinground:response.ongoinground,
            status:response.status,
            teamsregistered:response.teamsregistered
        })
       console.log(data.teamsregistered) // it shows "undefined"

when i run console.log(data.teamsregistered) it shows 'undefined'.how to set in the state hook and acces every element in it.

Patrick Roberts
  • 49,224
  • 10
  • 102
  • 153
Mohan Raj
  • 167
  • 12
  • 3
    State changes are asynchronous, you can't `console.log` them on the next line. Print the state in the main body of the function to see latest value – Jayce444 Feb 18 '21 at 05:58
  • Try something like this `console.log(data?.teamsregistered)` – Florin Feb 18 '21 at 06:02
  • Does this answer your question? [useState set method not reflecting change immediately](https://stackoverflow.com/questions/54069253/usestate-set-method-not-reflecting-change-immediately) – Patrick Roberts Feb 18 '21 at 06:08

1 Answers1

2

when i run console.log(data.teamsregistered) it shows 'undefined'.how to set in the state hook and acces every element in it.

This is happing because setState() hook is asynchronous. So if you want to see the update you have to use useEffect() Hook to see the update in the state like:-

.then(response => {
        console.log(response.teamsregistered) //it shows correct output
        setData({...data,
            name:response.name,
            date:response.date,
            ongoinground:response.ongoinground,
            status:response.status,
            teamsregistered:response.teamsregistered
        })
useEffect(() => { console.log(data.teamsregistered) }, [data])