0

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

2 Answers 2

1

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?

Sign up to request clarification or add additional context in comments.

1 Comment

YES!! Thank you!!
1
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.

1 Comment

yessss you got it right! thank you! <3

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.