Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

112
Visualizações
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 Respostas
Responde à pergunta

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 Relatório

0

return [
  { 
    ...(state[0] || {}),
    data: {
      id: Math.floor(Math.random() * 999),
      name: payload.name
    } 
  },
  ...state?.slice?.(1)
]
about 4 years ago · Juan Pablo Isaza Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda