Below code, I update the react hook with if-else shorthand condition. To understand exactly this, I try to write it in normal if-else condition, but I couldn't. What is the equal case of this shorthand conditions?
This is working code.
const [array, setArray] = useState([]);
function addProduct(product){
const ProductExist = array.find((item) => item.id === product.id);
setArray(
array.map((item) =>
item.id === product.id
? { ...ProductExist, quantity: ProductExist.quantity 1 }
: item
)
);
}
This is my try according to the solutions of other topics. But it gives error.
setTestArray(array.map((item) => {
return if(item.id === product.id){
return { ...ProductExist, quantity: ProductExist.quantity 1 }
}else{
return item
}
}
CodePudding user response:
setArray(
array.map((item) =>
if(item.id === product.id){
return { ...ProductExist, quantity: ProductExist.quantity 1 }
} else {
return item
}
)
<iframe name="sif1" sandbox="allow-forms allow-modals allow-scripts" frameborder="0"></iframe>
CodePudding user response:
You have an extra return
It should be like this:
setTestArray(array.map((item) => {
if(item.id === product.id){
return { ...ProductExist, quantity: ProductExist.quantity 1 }
}else{
return item
}
}))