0

I am trying to have items be addable (done) however I am having an issue with trying to remove an item from the users cart.

Removefromcart = (cart, id) => {
    // using an updater function
    this.setState(({
      // keep everything except the item with the id that was passed in
      cart: this.state.cart.filter(cart => cart.id !== id),
      
      // item price - current state total
     // total: state.total - price
    }));
  };

As you can see I am trying to use a filter to remove everything except the id of what was clicked. However right now it seems to be erasing the array completely. Before that it wasn't affecting the array at all. In case it is relevant here is a link to my full code: https://codesandbox.io/s/vigilant-dubinsky-0d57h

Heretic Monkey
  • 11,687
  • 7
  • 53
  • 122
imstupidpleasehelp
  • 1,618
  • 2
  • 16
  • 36
  • In the sandbox you're not using an arrow function, once you change it to an arrow function everything works... (or bind it in the constructor...) – SakoBu Jul 16 '20 at 19:47
  • If I change it to an arrow function it changes from doing nothing to erasing everything, which is the only two outcomes I can produce. – imstupidpleasehelp Jul 16 '20 at 20:04

1 Answers1

1

Because this.props and this.state may be updated asynchronously, you should not rely on their values for calculating the next state.

docs

To fix it, use a second form of setState() that accepts a function rather than an object. That function will receive the previous state as the first argument, and the props at the time the update is applied as the second argument: Blockquote

In your case, you'll need:

this.setState(prevState => ({
  cart: prevState.cart.filter(cart => cart.id !== id),
});
V Maharajh
  • 9,013
  • 5
  • 30
  • 31
  • Please at least do a cursory search for duplicates before answering. – Heretic Monkey Jul 16 '20 at 19:48
  • Will do @HereticMonkey, but FWIW I don't think the suggested duplicate addresses OPs question. – V Maharajh Jul 16 '20 at 19:58
  • I think it's close enough, I will refer to the resources that you guys both gave me here. Thank you. Just one last little question, why is this returning a syntax error? I can't figure out why. ``` Removefromcart = () => { this.setState(prevState => ({ cart: prevState.cart.filter(cart => cart.id !== id) }) } ``` – imstupidpleasehelp Jul 16 '20 at 20:00
  • You're missing a `)`. This works: Removefromcart = () => { this.setState(prevState => ({ cart: prevState.cart.filter(cart => cart.id !== id) }) )} – V Maharajh Jul 16 '20 at 20:31