State immutability is very important when it comes to working with React. It's easy to follow when working with primitive data types, but an untrained user may have difficulty with composite ones, such as objects and arrays.
This lesson discusses the ways to update objects and arrays partially. In addition to examples in pure JavaScript, we'll also show how to use the immutability-helper
library to facilitate such operations. It helps to work with upgrades where the JavaScript code is too complex.
The simplest method is adding to an array:
const items = ['one', 'two', 'three'];
const item = 'four';
const newItems = [...items, item];
// ['one', 'two', 'three', 'four'];
If you want to add an element to the beginning, all you have to do is swap the elements of the array:
const newItems = [item, ...items];
// ['four', 'one', 'two', 'three'];
import update from 'immutability-helper';
const state1 = ['x'];
const state2 = update(state1, { $push: ['y'] }); // ['x', 'y']
It is a more curious example. If you want to remove an element from an array, you should know what to remove. It means that each item in the collection must have an identifier. We can use good old-fashioned filtering to delete something:
const newItems = items.filter((item) => item.id !== id);
You may be wondering where the identifier inside the handler came from. And this is where closure comes to our aid:
See the Pen js_react_immutability_array_remove_element by Hexlet (@hexlet) on CodePen.
Note the way the handler is set: removeItem = (id) => (e) => {
and its use of onClick={this.removeItem(id)}
.
const index = 5;
const newItems = update(items, {$splice: [[index, 1]]});
In clean JavaScript, deleting using a filter is the best way. Using immutability-helper
is too complicated.
Unfortunately, if we do not have any additional tools, the code for our solution will get too cumbersome. We're showing it here for reference, but you shouldn't do this in real projects:
const index = items.findIndex((item) => item.id === id);
const newItem = { ...items[index], value: 'another value' };
const newItems = [...items.slice(0, index), newItem, ...items.slice(index + 1)];
We imagine we won't have to convince you that this is too much :)
const collection = { children: ['zero', 'one', 'two'] };
const index = 1;
const newCollection = update(collection, { children: { [index]: { $set: 1 } } });
// { children: ['zero', 1, 'two'] }
As you can see, this method is much easier and cleaner, so we recommend to use it.
It is just as simple as with arrays:
const items = { a: 1, b: 2 };
const newItems = { ...items, c: 3 };
// { a: 1, b: 2, c: 3 }
Or you can do this, if the key is calculated dynamically:
const items = { a: 1, b: 2 };
const key = 'c';
const newItems = { ...items, [key]: 3 };
// { a: 1, b: 2, c: 3 }
Here destructuring comes to the rescue:
const { deletedKey, ...newState } = state;
import update from 'immutability-helper';
const state = { a: 1, c: 3 };
const updatedState = update(state, {
$unset: ['c'],
});
// { a: 1 }
It is the same as adding:
const items = { a: 1, b: 2 };
const newItems = { ...items, a: 3 };
// { a: 3, b: 2 }
const data = { a: 1, b: 2 };
const key = 'a';
const newData = update(data, { [key]: { $set: 3 } });
// { a: 3, b: 2 }
In the examples above, you can mostly make do with the standard JavaScript tools' it's only more convenient to use third-party solutions in certain situations. It is the same in real projects, especially if you consider React's recommendations and keep the state as flat as possible.
In some situations, the data that needs to be changed isn't on the surface but deep within the structures. Unfortunately, regular JavaScript code will be huge in these situations, so you can't do without additional libraries.
import update from 'immutability-helper';
const myData = {
x: { y: { z: 5 } },
a: { b: [1, 2] },
};
const newData = update(myData, {
x: { y: { z: { $set: 7 } } },
a: { b: { $push: [9] } }
});
console.log(newData)
// => { x: { y: { z: 7 } }, a: { b: [ 1, 2, 9 ] } }
https://repl.it/@hexlet/js-react-immutability-helper
The library immutability-helper
isn't the only one for such tasks. Here are a few more popular tools:
The Hexlet support team or other students will answer you.
A professional subscription will give you full access to all Hexlet courses, projects and lifetime access to the theory of lessons learned. You can cancel your subscription at any time.
Programming courses for beginners and experienced developers. Start training for free
Our graduates work in companies:
Sign up or sign in
Ask questions if you want to discuss a theory or an exercise. Hexlet Support Team and experienced community members can help find answers and solve a problem.