ayabbear
ayabbear

Reputation: 318

Adding an array and an object to an array react hooks

I'm trying to add an array and an object to an array.

This is my constructor

const [dashboard, setDashboard] = useState({ loading: true, data: [], address: '' })

and this is how I wanted the data to end up

{
   loading: true,
   data: [{id: 0, name: 'A'}, {id: 1, name: 'B'}],
   address: 'xxx'
}

I can't seem to figure it out and was only able to manage to add the arrays but not the other objects like loading and address with something like this but this is not what I need and I'm just giving an example of what I tried doing:

the constructor of this one in the bottom is different from what I want to use, I used something like this

const [dashboard, setDashboard] = useState([])

setDashboard((prev) => {
   return [...prev, newData]
})

Upvotes: 0

Views: 209

Answers (2)

ajthyng
ajthyng

Reputation: 1275

const [dashboard, setDashboard] = useState({ loading: true, data: [], address: '' })

The line above looks great, no problems there.

setDashboard((prev) => {
   return [...prev, newData]
})

Doing this will set your dashboard variable to be an array, and is definitely not what you said you wanted.

setDashboard((prev) => {
  return {
    ...prev,
    data: [...prev.data, ...newData] // <-- assuming new data is an array
  }
})

Depending on what newData looks like you may need to manually merge the data into your previous data object. For instance, if you want to ensure you have no duplicate values in the array, or you need to sort them.

Upvotes: 1

HOERNSCHEN
HOERNSCHEN

Reputation: 937

If I understand your problem correctly you are trying to do something like this:

setDashbaord(prevDashboard => ({ ...prevDashboard, address: "xxx", data: [...prevDashboard.data, newData] }));

Is that what you are looking for?

Upvotes: 1

Related Questions