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
Having problem with IncreaseItem function

My result is seeing item.acf.count as string and not as number. How can I convert this to number?

Here is the function below.

increaseItem = (id) => {
    const { cart } = this.state;
    cart.forEach(item => {
        if (item.id === id) {
            item.acf.count += 1
                
        }
    })
    this.setState({
        cart:cart
    })
}
about 4 years ago · Juan Pablo Isaza
1 Respostas
Responde à pergunta

0

My result is seeing item.acf.count as string and not as number. please how can I convert is to number

You should ensure that the initial item.acf.count state is a number type so this count: item.acf.count + 1 operation works correctly and returns a number type. So long as your state updaters maintain the state invariant of item.acf.count being a number it should work as expected.

Additionally, the increaseItem handler is mutating the cart state and not creating new array/object references.

increaseItem = (id) => {
  const { cart } = this.state; // <-- cart is reference to cart state
  cart.forEach(item => {
    if (item.id === id) {
      item.acf.count += 1; // <-- mutation!
    }
  });
  this.setState({
    cart: cart // <-- cart state reference back into state
  })
}

You should instead shallow copy the cart and then also shallow copy the cart item (any any other nested properties) you want to update. I also suggest using a functional state update so you are correctly updating from the previous state and not any state value closed over in increaseItem callback scope.

increaseItem = (id) => {
  this.setState(prevState => ({
    cart: prevState.cart.map(item => item.id === id
      ? {
        ...item,
        acf: {
          ...item.acf,
          count: item.acf.count + 1
        }
      }
      : item),
  }));
}
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