Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

153
Vistas
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
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda