Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

113
Vistas
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 Respuestas
Responde la pregunta

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 Denunciar

0

return [
  { 
    ...(state[0] || {}),
    data: {
      id: Math.floor(Math.random() * 999),
      name: payload.name
    } 
  },
  ...state?.slice?.(1)
]
about 4 years ago · Juan Pablo Isaza Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda