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

77
Visualizações
How do I update array inside object in redux

I have an array I'm writing a code for redux now.

const initialState = [{ id: '1', title: '', description: '' }];

I would like to update that array like this

[{ id: '1', title: '', description: '' },{ id: '2', title: '', description: '' }];

and after copying I want to update the copy one of id to '2'

here is what I tried

    case COPY_QUESTION: {
      const copyQuestion = state.find(question => question.id === action.payload)
      copyQuestion?.id = (state.length + 1).toString()
      return [...state, copyQuestion];
    }

it didn't work for me. if I try to change id, the 0 index changes too at the same time. like this

[{ id: '2', title: '', description: '' },{ id: '2', title: '', description: '' }];

I would really appreciate your help thanks for reading this question.

about 4 years ago · Juan Pablo Isaza
2 Respostas
Responde à pergunta

0

Something like this should work:

const initialState = [{ id: '1', title: '', description: '' }];

const copyInitialState = [...initialState]

copyInitialState.push({ id: parseInt(copyInitialState[copyInitialState.length - 1].id, 10) + 1, title: '', description: '' })

//setState

copyInitialState is then equal to:

[
 {
  id:"1",
  title:"",
  description:""
 },
 {
  id:2,
  title:"",
  description:""
 }
]
about 4 years ago · Juan Pablo Isaza Relatório

0

JavaScript handels Objects by reference and therefore ’find’ only returns the address in memory of the already existing object, which you then manipulate.

You have to clone your object first, e.g. using the spread operator (not for deep clones):

const originalQuestion = state.find(question => question.id === action.payload)
const copyQuestion = { ...originalQuestion }

Have a look at this SO question for more context and possibilities.

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