Mohan Raj
Mohan Raj

Reputation: 197

How to add array of objects in react state hook?

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.

Upvotes: 0

Views: 84

Answers (1)

Kushagra Mehta
Kushagra Mehta

Reputation: 62

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])

Upvotes: 2

Related Questions