Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

163
Views
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 answers
Answer question

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 Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!