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

184
Visualizações
Finding a specific object in state, removing it and replacing it in React

My current code finds an object in a state array, removes it and then adds a newValue in its place. I know using .splice() mutates the state directly which is not a recommended practice in React. What is the proper way to do what I am trying to do below?

      const found = clientServiceReferral.selectedTimeSlots.find(element => element.timeSlot === timeWithDate);

      if (found) {
        clientServiceReferral.selectedTimeSlots.splice(found, 1)
      }


      const newValue = {
        timeSlot: timeWithDate,
        value: value.value
      }

      setClientServiceReferral({
        ...clientServiceReferral,
        selectedTimeSlots: [...clientServiceReferral.selectedTimeSlots, newValue]
      })
about 4 years ago · Juan Pablo Isaza
1 Respostas
Responde à pergunta

0

I would use map method, which returns a new array, to find and replace:

const updatedTimeSlots = clientServiceReferral.selectedTimeSlots.map((element) => {
    if(element.timeSlot === timeWithData){
      return {timeSlot: timeWithDate, value: value.value}
    } else {
      return element
    }
})
setClientServiceReferral({
    ...clientServiceReferral,
    selectedTimeSlots: updatedTimeSlots
})
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