0

I am an app where I a user can add a productItem to a Basket. At the moment if the user removes an item from the basket I am using .filter to remove the basketItem object from my basketItems array. I then setState to this array with the filtered item.

removeItem(msg, data) {
    let newStateItems = this.state.items.filter((i) => i.id != data.id); 
    this.setState({
        items: newStateItems
    });
    this.calculateTotals();
}

The issue however is that once I have removed an item and then go to add another Item, the new Item that is created shows as the old item until the page is refreshed - an example this app can be found here and the full repository is on github.

The add item call looks like this:

addItem(msg, data) {
    this.state.items.push(data);
    this.setState({
        items: this.props.items
    })
    this.calculateTotals();
}

How can I ensure that the correct item shows in the basket?

Tom Pinchen
  • 2,467
  • 7
  • 33
  • 53
  • maybe you need add item something like this https://jsfiddle.net/7og8ztLz/ – Oleksandr T. Apr 12 '16 at 09:48
  • Use `concat` instead `push` in react. `push` mutates values. But React works with immutable data (It works with mutable data, but I don't recomend you to look for problems) – iofjuupasli Apr 12 '16 at 10:42

1 Answers1

0

Ok, I think you have two problems:

  1. You're calling calculateTotals synchronously, i.e. before the state object is updated
  2. You're setting the state to be this.props.items

I would recommend the following:

removeItem(msg, data) {
    let newStateItems = this.state.items.filter((i) => i.id != data.id); 
    this.setState({
        items: newStateItems
    }, this.calculateTotals);
}

AND

addItem(msg, data) {
    let newStateItems = this.state.items.concat([data]); 
    this.setState({
        items: newStateItems
    }, this.calculateTotals);
}

Notice how this.calculateTotals is now sent to setState, which then calls it after updating the state, but also that addItem now sets the state using a modified list and not the props as it was before (I assume this was a minor typo, but it probably contributed).

Here is the documentation for setting state: https://facebook.github.io/react/docs/component-api.html#setstate

Neil Twist
  • 1,099
  • 9
  • 12