I am trying to add things to a list, in the form of a state array. However, with my current code, the first item doesn't add itself properly.
export default class Main extends React.Component {
constructor(props) {
super(props);
this.state = {
list: [],
total: 0.00,
...
}
}
//some unimportant code here
addToList = item => {
this.setState({list: [...this.state.list, item]});
//This method call for a method that gets the total price of all the items
this.getTotal();
}
//this method works fine, except with the first element
getTotal() {
this.setState(({sum= 0.0, items, list}) => {
items.forEach(element => {
if(this.state.list.length !== 0.0) {
if(this.state.list.includes(element.name)) {
sum += parseFloat(element.price);
}
}
});
this.setState({total: sum});
});
}
}
When I console.log
the list
state I get an empty array for the first item, and then the items are delayed by one. So if I add the item A
and look at the console, I see nothing. When I add item B
and look at the console, I see an Array
with the item A
. Any ideas as to what is causing this?