3
The main idea is based on a shopping cart, when a product is added to the cart (key products
) the key orderTotal
is updated.
Inside the key products
own a object
with various products each containing the value, and the total of purchase products: ordered
and price
, example:
state = {
products: {
"a": {
name: "A",
price: 2
ordered: 5
},
"b": {
name: "B",
price: 5,
ordered: 2
}
},
orderTotal: 0
}
I tried to put a reduce()
inside componentWillUpdate()
, but I can’t use this.setState()
inside componentWillUpdate()
because it 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 products
is updated, perform a loop by calculating ordered * price
and store the sum of everything in orderTotal
, what method I can use?
The Cart component receives the product object via props?
– Miguel Angelo
@Not Miguelangelo, the state
orderTotal
is only in the parent component is not passed to any other component.– RFL
But what about the object products? Where he comes from?
– Miguel Angelo
It is started empty through the builder, for the user to add products I pass a function to a child component that manages to add other objects within products
– RFL