Reputation: 395
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!
Upvotes: 0
Views: 2606
Reputation: 5497
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
);
Upvotes: 1
Reputation: 5108
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. :)
Upvotes: 1