Solution found below
I am making an add/remove item from cart system.
const handleClick = (i) => {
if (i >= 0 && i <= itemQuantity) {
console.log("i : " + i);
setQty(i);
}
};
useEffect(() => {
if (qty >= 1) {
dispatch(addToCart(product._id, qty));
} else {
dispatch(removeFromCart(product._id));
}
}, [qty]);
<button onClick={() => handleClick(qty - 1)}>Substract</button>
<img src={product.image} alt={product.name} />
<button onClick={() => handleClick(qty + 1)}>Add</button>
If I use the buttons slowly, I get a very satysfying result (I cannot substract anymore and Cart is empty) :
But if I click on the substract button quickly, things go funky, not sure why (I am not trying to go below 0, I exactly click the right number of time to go to qty=0):
Then I cannot substract more, and quantity gets stuck to 1.
export const addToCart = (productId, qty) => async (dispatch, getState) => {
const { data } = await Axios.get(`/api/prints/${productId}`);
const {
cart: { cartItems },
} = getState();
dispatch({
type: CART_ADD_ITEM,
payload: {
name: data.name,
image: data.image,
price: data.price,
countInStock: data.countInStock,
product: data._id,
seller: data.seller,
qty,
},
});
localStorage.setItem("cartItems", JSON.stringify(getState().cart.cartItems));
};
export const removeFromCart = (productId) => (dispatch, getState) => {
dispatch({ type: CART_REMOVE_ITEM, payload: productId });
localStorage.setItem("cartItems", JSON.stringify(getState().cart.cartItems));
};
Edit - Solution :
dispatch(addToCart(product._id, qty)).then(() => setLoad(false));
<button
disabled={load}
onClick={() => {
setLoad(true);
handleClick(qty - 1);
}}
>