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 basic ways to partially update objects and arrays.
In addition to examples in pure JS, we'll also show examples using the immutability-helper
library, which is designed to facilitate such operations. It's especially useful for upgrades where the JS 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']
This is a more interesting example. If you want to remove an element from an array, you need to know what to remove. This 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 JS, deleting using a filter is the best way. Using immutability-helper
is difficult.
Unfortunately, if we don't 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 code.
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)];
I imagine I 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. Recommended for use.
This 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, if the key is calculated dynamically, you must do this:
const items = { a: 1, b: 2 };
const key = 'c';
const newItems = { ...items, [key]: 3 };
// { a: 1, b: 2, c: 3 }
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 }
Exactly 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 JS tools' it's only more convenient to use third-party solutions in certain situations. This is the same in real code, especially if you consider React's recommendations and keep the state as flat as possible. But in some situations, the data that needs to be changed isn't on the surface, but deep within the structures. Unfortunately, in these situations, normal JS code will be bloated. And here 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
immutability-helper
isn't the only library for such tasks. Here are a few more popular ones:
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:
From a novice to a developer. Get a job or your money back!
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.