0

I have a prototype e-commerce shopping cart with item and number of items to be purchased. There is a list of items each with a value (number of items to be purchased), an increment button and a delete button. I am trying to add a reset button which will set the values to zero.

I have written a handleReset function achieve this feature.

state = {
    counters: [
      { id: 1, value: 0 },
      { id: 2, value: 9 },
      { id: 3, value: 2 },
      { id: 4, value: 3 }
    ]
  };

handleReset = () => {
    let counters = [...this.state.counters];
    counters = counters.map((counter, index) => {
      counter.id, 0;
    });
    this.setState({ counters });
  };

/* I need the state to look like this: */

state = {
    counters: [
      { id: 1, value: 0 },
      { id: 2, value: 0 },
      { id: 3, value: 0 },
      { id: 4, value: 0 }
    ]
  };

When I tried handleReset as above I get the error:

Failed to compile
./src/components/counters.jsx
  Line 29:  Expected an assignment or function call and instead saw an expression  no-unused-expressions

Search for the keywords to learn more about each error.
jonrsharpe
  • 115,751
  • 26
  • 228
  • 437
Bhushan KC
  • 21
  • 3
  • 1
    Your `map` callback doesn't return an object - `=> ({ ... })` is an object, `=> { ... }` is a regular function body. It's not just a linting problem, your code doesn't work. – jonrsharpe Jun 04 '19 at 08:33

2 Answers2

0

So you can change your handleReset method as per below, as you need to return while using map :

handleReset = () => {
  let counters = [...this.state.counters];
  counters = counters.map((counter, index) => {
    return {id: counter.id, value: 0};
  });
  this.setState({ counters });
};

or you can write it in another form as:

handleReset = () => {
  let counters = [...this.state.counters];
  counters = counters.map((counter) => ({id: counter.id, value: 0}));
  this.setState({ counters });
};
0

Your handleReset should look like this one :

handleReset = () => {
  const newCounters = this.state.counters.map(counter=>
    ({id: counter.id, value: 0})
  )
  this.setState({counters: newCounters})
};

Also try to make immutable methods, as describe here : Why is immutability so important (or needed) in JavaScript?

benjamin Rampon
  • 1,316
  • 11
  • 18