Detecting changes

What's special about mutative methods, or methods that perform persistent changes, is that they return the same collection instance if nothing actually changes. This is a big deal because it means that you can use strict equality to detect a change in the collection, as shown here:

const myList = List.of(1, 2, 3);
const myMap = Map.of(
'one', 1,
'two', 2,
'three', 3
);
const myModifiedList = myList.push(4);
const myModifiedMap = myMap.set('four', 4);

console.log('myList', myList.toJS());
// -> myList [ 1, 2, 3 ]
console.log('myMap', myMap.toJS());
// -> myMap { one: 1, two: 2, three: 3 }
console.log('myModifiedList', myModifiedList.toJS());
// -> myModifiedList [ 1, 2, 3, 4 ]
console.log('myModifiedMap', myModifiedMap.toJS());
// -> myModifiedMap { one: 1, two: 2, three: 3, four: 4 }
console.log(
'myList === myModifiedList',
myList === myModifiedList
);
// -> myList === myModifiedList false
console.log(
'myMap === myModifiedMap',
myMap === myModifiedMap
);
// -> myMap === myModifiedMap false

We have two initial collections in this example: myList and myMap. We then proceed to call mutative methods on these collections and store the results. The list gets a new value via the push() method and the map gets a new key-value pair via the set() method. When you compare the initial collections with their corresponding changed collections, you can see that they're not equal—the strict equality operator returns false in both instances. This is the expected behavior, because we changed the collections by adding new values.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
18.191.94.249