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.

3
  • 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 Commented Feb 18, 2021 at 5:58
  • Try something like this console.log(data?.teamsregistered) Commented Feb 18, 2021 at 6:02
  • Does this answer your question? useState set method not reflecting change immediately Commented Feb 18, 2021 at 6:08

1 Answer 1

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

Comments

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.