Immer Video Tutorial
In this video I invite you to discover Immer. This library will allow you to create immutable functions using the mutable functions of JavaScript.
The problem
When we want to work with pure functions we sometimes find ourselves with more complex functions than necessary.
function toggleTodo (state, index) {
if (index> = state.todos.length) {
return state
}
return {
... state,
todos: state.todos.map ((todo, i) =>
i === index
? {
... todo,
completed:! todo.completed
}
: todo
)
}
}
JavaScript is not necessarily designed with immutability as the main concept and it is often much easier to write the same code in a mutable way.
function toggleTodo (state, index) {
state.todos (index) .completed =! state.todos (index) .completed
return state
}
Immer to the rescue
Immer will allow you to work with mutations while keeping the functions immutable. For this, it relies on a Proxy system which will act as an intermediary towards the original object.
import {produce} from 'immer'
function toggleTodo (state, index) {
return produce (state, function (draft) {
draft.todos (index) .completed =! draft.todos (index) .completed
})
}
This function uses the principle of currying and will return a function if it is called with only one argument.
import {produce} from 'immer'
const toggleTodo = produce (function (draft, index) {
draft.todos (index) .completed =! draft.todos (index) .completed
})
To learn more, do not hesitate to take a look at the documentation