0

I have a product and i want to get the total price of this product based on quantity, I'm using zustand for state management.

here's a function I used to update the state.

export const useCartProduct = create<CartProductsProp>(
  devtools(
    persist(
       (set) => ({
         incrementProductQuantity: (product: ProductProps) => {
          set((prev) => {
            console.log('@userQuantity-product', product.userQuantity);
            let currentCart = prev.cartProducts.map((cartProduct) =>
              cartProduct.id === product.id
                ? {
                    ...cartProduct,
                    userQuantity: cartProduct.userQuantity + 1,
                    productTotalPrice: cartProduct.userQuantity * cartProduct.price, // here's the issue "the userQuantity not updated and return the prev value".
                  }
                : cartProduct,
            );
            return {
              cartProducts: currentCart,
            };
          });
        },
      }),
    ),
  ),
);

the issue here

  productTotalPrice: cartProduct.userQuantity * cartProduct.price

"the userQuantity not updated and return the prev value".

So what I tried is like this

  productTotalPrice: (cartProduct.userQuantity + 1) * cartProduct.price,

that's return the correct quantity 'updated one', So is others way to fix it?

Linda Paiste
  • 38,446
  • 6
  • 64
  • 102
Oliver D
  • 2,579
  • 6
  • 37
  • 80
  • Try to read about React Hooks. To be specific, `useState` hook: https://reactjs.org/docs/hooks-state.html Then, combine it with `useEffect` Hook: https://reactjs.org/docs/hooks-effect.html – Jerry Ben Mar 08 '21 at 23:18
  • 1
    @JerryBen But it's not related specifically to my issue (with zustand) – Oliver D Mar 09 '21 at 11:30

0 Answers0