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

81
Views
componentDidMount affects other component

I have a price counter component. When I try to decrease a product qty to 0 it is deleted successfully but it affects the following product's qty and gives it 0, not its actual qty.

// Component
handleIncrement = () => {
  this.setState({ qty: this.state.qty + 1 });
};

handleDecrement = () => {
  this.setState({ qty: this.state.qty - 1 });
};

componentDidUpdate(prevProps, prevState) {
  const { cartId, getQty, updateQty } = this.props;
  const { qty } = this.state;

  if (prevState.qty !== qty) {
    if (getQty) getQty(qty); // Parent CB
    if (this.props.qty) updateQty({ cartId, qty });
  }
}

// Action
export const updateQty = (item) => (dispatch, getState) => {
  dispatch({ type: CART_UPDATE_QTY, payload: item });
};

// Reducer
case CART_UPDATE_QTY:
  const { cartId, qty } = action.payload;

  // In case of qty = 0 => delete item & return new cart
  if (qty <= 0) {
    const newCart = cart.filter((p) => p.cartId !== cartId);
    localStorage.setItem("cart", JSON.stringify(newCart));
    return newCart;
  }

  // Update Qty
  const item = cart.find((p) => p.cartId === cartId);
  item.qty = qty;
  const filteredCart = cart.filter((p) => p.cartId !== cartId);
  const updatedCart = [...filteredCart, item];
  localStorage.setItem("cart", JSON.stringify(updatedCart));
  return updatedCart;
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!