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

150
Views
Dispatch called without explications when button clicked quickly

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

enter image description here

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

enter image description here

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);
              }}
            >
about 4 years ago · Juan Pablo Isaza
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!