Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

151
Visualizações
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 à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda