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

111
Views
How to spread state into a specific array

I've got an array of objects and when a certain functions called I want to update a specific array within that array of objects with new data.

Heres the call:

const DataReducer = (state, action) => {
  switch (action.type) {
    case 'ADD_DATA':
      return [...state, state[0].data:[...state, {id: Math.floor(Math.random() * 999),
        name: action.payload.name,
   }]];
  }
}

The problem is I keep getting an error "',' Expected", this appears on the : after data I'm pretty sure this is correct though, I'm using the context api to update some existing state with new names when the addName function is called. This should spread the existing state and take the specific state from item[0].data, adding the new name to it but I cant seem to get it working.

Any help would be appreciated.

Here's the original data object: [{title: 'Names', data: []}, {title: 'Meal', data: []}]

about 4 years ago · Juan Pablo Isaza
2 answers
Answer question

0

It might be easier to break up that return. Make a copy of the state, create an object, and add that to the data array, preserving any objects that are already in there. Then return the copy to update the state.

const DataReducer = (state, action) => {

 const { type, payload } = action; 

 switch (type) {

    case 'ADD_DATA': {

      const copy = [...state];

      copy[0] = {
        ...copy[0], 
        data: [
          ...copy[0].data, {
            id: Math.floor(Math.random() * 999),
            name: 'Bob'
          }
        ]
      };

      return copy;

    }
  }
}

const state = [{title: 'Names', data: []}, {title: 'Meal', data: []}];

const newState = DataReducer(state, { type: 'ADD_DATA', payload: { name: 'Bob' } });

console.log(newState);

about 4 years ago · Juan Pablo Isaza Report

0

return [
  { 
    ...(state[0] || {}),
    data: {
      id: Math.floor(Math.random() * 999),
      name: payload.name
    } 
  },
  ...state?.slice?.(1)
]
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!