简体   繁体   中英

Getting a total price of cart products

I am working on a project here and I ran into a little issue. Now I need to get the price of all items in the cart and add it together to make a "total: {price}", and well. My brain is just completely still at the moment.

Now here is the code I am using:

  const { cartItems } = useContext(AddToCartContext);
  const [totPrice, setTotPrice] = useState(0);

  let cart = cartItems.filter(
    (ele, ind) => ind === cartItems.findIndex((elem) => elem.id === ele.id)
  );

  useEffect(() => {
    cart.forEach((item) => {
      setTotPrice(totPrice + item.price);
      console.log(item.price);
    });
  }, []);

  console.log(`${totPrice}`);

I am very aware that this does not work, as the totPrice useState is resetting itself to 0, as its the initial value. But I am not really sure how I can tackle this?

I need it to take all products, which could perhaps be 10 products. And then add the price of all those 10 products, to get a total.

Any ideas can help!

you don't need an additional state here. All you need is an derived value from the state.

const { cartItems } = useContext(AddToCartContext);

let cart = cartItems.filter(
  (ele, ind) => ind === cartItems.findIndex((elem) => elem.id === ele.id)
);

const totalPrice = cart.reduce(
 (totalPrice, item) => totalPrice + item.price,
 0
);

Use Array.prototype.reduce: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/Reduce

let totalPrice = cartItems.reduce((total, cartItem) => total + cartItem.price);
setTotPrice(totalPrice);

Ah another answer beat me to it. :)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM