Having problem with IncreaseItem function

Viewed 29

My result is seeing item.acf.count as string and not as number. How can I convert this to number?

Here is the function below.

increaseItem = (id) => {
    const { cart } = this.state;
    cart.forEach(item => {
        if (item.id === id) {
            item.acf.count += 1
                
        }
    })
    this.setState({
        cart:cart
    })
}
1 Answers

My result is seeing item.acf.count as string and not as number. please how can I convert is to number

You should ensure that the initial item.acf.count state is a number type so this count: item.acf.count + 1 operation works correctly and returns a number type. So long as your state updaters maintain the state invariant of item.acf.count being a number it should work as expected.

Additionally, the increaseItem handler is mutating the cart state and not creating new array/object references.

increaseItem = (id) => {
  const { cart } = this.state; // <-- cart is reference to cart state
  cart.forEach(item => {
    if (item.id === id) {
      item.acf.count += 1; // <-- mutation!
    }
  });
  this.setState({
    cart: cart // <-- cart state reference back into state
  })
}

You should instead shallow copy the cart and then also shallow copy the cart item (any any other nested properties) you want to update. I also suggest using a functional state update so you are correctly updating from the previous state and not any state value closed over in increaseItem callback scope.

increaseItem = (id) => {
  this.setState(prevState => ({
    cart: prevState.cart.map(item => item.id === id
      ? {
        ...item,
        acf: {
          ...item.acf,
          count: item.acf.count + 1
        }
      }
      : item),
  }));
}
Related