Search⌘ K

ES6 Spread Operators

Explore how to effectively use ES6 spread operators to manage and update complex state objects in React without mutating original data. Understand the difference between array and object spreads and how they simplify state updates, enabling you to fix issues like the 'Dismiss' button not working properly in your app.

We'll cover the following...

The “Dismiss” button doesn’t work because the onDismiss() method is not aware of the complex result object. It only knows about a plain list in the local state. But it isn’t a plain list anymore. Let’s change it to operate on the result object instead of the list itself.

Javascript (babel-node)
onDismiss(id) {
const isNotId = item => item.objectID !== id;
const updatedHits = this.state.result.hits.filter(isNotId);
this.setState({
...
});
}

In setState(), the result is now a complex object, and the list of hits is only one of multiple properties in the object. Only the list gets updated when an item gets removed in the result object, though, while the other properties stay the same.

We could alleviate this challenge by mutating the hits in the result object. It is demonstrated ...