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
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