The main idea is based on a shopping cart, when a product is added to the cart (key products
) the key orderTotal
is updated.
Within the products
key I have a object
with several products that each contain the value, and total purchase products: ordered
and price
, for example:
state = {
products: {
"a": {
name: "A",
price: 2
ordered: 5
},
"b": {
name: "B",
price: 5,
ordered: 2
}
},
orderTotal: 0
}
I've tried to put reduce()
inside componentWillUpdate()
, but I can not use this.setState()
within componentWillUpdate()
since this generates an infinite loop.
componentWillUpdate () {
const products = {...this.state.products};
const orderTotal = Object.keys(products).reduce((sum, next) => {
return sum + (products[next].ordered * parseFloat(products[next].price));
}, 0);
this.setState({ orderTotal }); // Loop infinito.
}
I need every time that products
is updated, looping by compiling ordered * price
and storing the sum of everything in orderTotal
, what method can I use?