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

146
Visualizações
Conditionally add key/value pairs of two separate objects (one in array within initial state) for array method inside of useState() hook

Right now, this doesn't work.

const item = {name: "mike", apples: 20}

const [list, setList] = useState([{name: "peter", apples: 30}, {name: "mike", apples: 39}])

setList(list.map(entry => entry.name == item.name ? entry.apples = item.apples+entry.apples : entry = entry))

I am able to get it working with the code below. I know it's not clean and that's why I'm trying to get the top code working the react way: using es6 within useState hook.

  let newList = [...list]
  let changed = false
  newList.map(entry => {
    if(entry.name == item.name) {
      entry.apples = item.apples+entry.apples
    }
  if(changed) {
    setList(newList)
  }

Edit: I've also tried functional update on the state like below

setList(list => list.map(entry => entry.name == item.name ? entry.apples = item.apples+entry.apples : entry = entry))
about 4 years ago · Juan Pablo Isaza
1 Respostas
Responde à pergunta

0

Here's the right way:

setList((previousList) =>
  previousList.map((entry) =>
    entry.name == item.name
      ? { ...entry, apples: entry.apples + item.apples }
      : entry
  )
);

entry.name == item.name ? entry.apples = item.apples+entry.apples

will not work because entry.apples = item.apples+entry.apples returns apples, but each element of the array should remain an object and you should also make sure that the state is not mutated (entry.apples = ... is bad because entry is mutated)

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