Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

160
Vistas
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 Respuestas
Responde la pregunta

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 Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda