I'm using immutability-helper for doing CRUD operations on state data and want to know if I should always use $splice
for removing data or is it ok to use filter
(since it's not destructive)?
For example, let's say I have an array of objects:
todos = [
{id: 1, body: "eat"},
{id: 2, body: "drink"},
{id: 3, body: "sleep"},
{id: 4, body: "run"}
]
Given an item id, I can remove it in two ways:
a. find its index
and use $splice
:
index = todos.findIndex((t) => { return(t.id === id) });
newtodos = update(todos, { $splice: [[index, 1]] })
OR
b. use filter
:
newtodos = todos.filter((t) => { return(t.id === id) });
filter
is more concise but I'm not sure if it has any disadvantages compared to using $splice
in this case.
There is a helper function update from immutability-helper which eases the code involved in state updates. The function takes the original state object and another object which specify the state changes. The second parameter has the same hierarchy as the original state object.
Besides reduced memory usage, immutability allows you to optimize your application by making use of reference- and value equality. This makes it really easy to see if anything has changed. For example a state change in a react component.
If an object is immutable, you cannot change its state or the value of its properties. However, this also means that you cannot add new properties to the object.
An immutable value or object cannot be changed, so every update creates new value, leaving the old one untouched. For example, if your application state is immutable, you can save all the states objects in a single store to easily implement undo/redo functionality.
use immutability-helper
:
it's convenient to process nested collection
:
const collection = [1, 2, { todos: [...todos] }];
const newCollection = update(collection, {
2: {
todos: {
$apply: todos => todos.filter(t => t.id !== id)
}
}
});
and, it give you a new copy for collection
and collection[2]
:
console.log(newCollection === collection, newCollection[2] === collection[2]);
//false false
So, if you use react-redux
, connect
state to component, if you want your component re-render when the state changed, you must return a new copy of state.
Do this operator with old way:
const todoList = collection[2].todos;
const idx = todoList.findIndex(t => t.id === id);
const newTodoList = update(todoList, { $splice: [[index, 1]] });
const newCollectionTwo = [...collection];
newCollectionTwo[2] = {
todos: newTodoList
};
and take a look with console:
console.log(collection, newCollectionTwo, collection === newCollectionTwo, collection[2] === newCollectionTwo[2]);
for simple data structure and operator, i think it's equal with filter
.
Sorry for my English is not good, and this is my opinion.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With