Why not send this action to the backend and just let inertia handle it? No need to do this in the browser manually
Feb 2, 2023
10
Level 8
ReactJS Var update in setItem not refreshing
On the console log, it shows that items has been changed with the amount incremented. But the objFound.amount ++; setItems(items); isn't detected as changed.
function handleAddProductToCart(product) {
let objFound = items.find(object => object.product_id === product.id);
if (objFound === undefined) {
let obj = {
cart_id: cart.id,
product_id: product.id,
amount: 1
}
let arr = [...items, obj]
setItems(arr);
}
else
{
// The problem is here
objFound.amount ++;
setItems(items);
}
}
Level 102
Oh and when working with data in react, you cannot mutate it. All data should be "immutable". So in your example, if you want to alter an object, you need to duplicate the array like you do here
let arr = [...items, obj]
but then swap out the item you want to alter with a changed on :)
I personally like to use immer, to change data before setting state https://immerjs.github.io/immer/
Please or to participate in this conversation.