Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

146
Views
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]
})
about 4 years ago · Juan Pablo Isaza
2 answers
Answer question

0

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.

about 4 years ago · Juan Pablo Isaza Report

0

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?

about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!