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

161
Visualizações
Javascript treats variable as string

I have the following state change operation:

const handleQuantity=(e)=>{
        const targetedProductId=e.target.id
        // console.log(targetedProductId)
        const targetedProductQuantity=e.target.value
       setOrderProductQuantity({
        ...orderProductQuantity,
        targetedProductId:targetedProductQuantity
        })
    }

and my state is this :

const [orderProductQuantity,setOrderProductQuantity]=React.useState({})

The

console.log(targetedProductId) 

shows the correct value

It always turns out that orderProductQuantity is updated with something like this: {"targetedProductId":e.target.value} instead of {e.target.id:e.target.value}. Could you please explain why this happens, how could I fix it ? Thank you !

P.S. Tried with string literals, also doesn't work

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

0

The problem is that you're not attributing the id value as the signatures of the parameter.

The correct way of doing so would be:

const handleQuantity = (e) => {
    const targetedProductId = e.target.id;
    const targetedProductQuantity = e.target.value;

    setOrderProductQuantity({
        ...orderProductQuantity,
        [targetedProductId]: targetedProductQuantity
    });
}

With the square brackets you're telling javascript that you want to map the value in targetedProductId, instead of actually writing targetedProductId

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