@meniga/immutable
v6.1.34-alpha.0
Published
## Immutable state changes
Downloads
1,104
Readme
@meniga/immutable
Immutable state changes
The purpose of these helpers is to make state changes in object more straight forward and more optimized for React rendering with shouldComponent update. The "change" methods always return a new reference if something has changed. But the references of things not changed stay the same.
There was/is a problem with assign methods used now that can cause a mutation of the object and keep the reference of arrays/objects. That will cause React to think nothing has changed
Example
const arr1 = [1]
const arr2 = arr[0] = 2
const state1 = assign({ items: arr })
const state2 = assign({ items: arr })
// state1.items === state2.items => true
This is the way it works but as we want the immutable way to optimize the rendering it is too easy to mutate. There are a lot of logic in the reducers doing simple things like updating an item in array or adding data to an item in array etc...
Immutable helpers
There are quite a few helpers, but you will probably only use a few of them often. The methods are curried so you can compose multiple changes in one go with the compose
method or composeState
method from reducer callback (more later in this readme)
These methods are really simple and only wrap some lodash/fp methods to create a consistent way and naming conventions. It is easier to pull all data chasing from one lib than pulling in some from lodash, lodash/fp, utils etc...
Example
This is good to change state inside a nested state. For arrays you would use findIndexIn
.
const state = {
isFetched: true,
items: [
{ id: 1, title: 'Title 1' },
{ id: 2, title: 'Title 2' },
]
}
// Notice the (state) at the end. The methods return functions
return updateIn(['items', findIndexIn('items', { id: 2 })], { title: 'Change title' })(state)
/*
{
isFetched: true,
items: [
{ id: 1, title: 'Title 1' },
{ id: 2, title: 'Changed title' },
]
}
*/
// Only items has changed
// => this.state.items === nextState.items => false
// => this.state.isFetched === nextState.isFetched => true
TODO
- allow predicate as 3rd parameter and that would find the index if needed
Composable
The other benefit of using the "fp" version of lodash methods is that it is easy to make the helpers compassable. That way you can return multiple state changes in one go
return compose(
updateIn(['items', 13, 'rules', 2], { active: false }),
mergeIn(['accounts', 3], { title: 'Account', meta: { show: false } }),
removeIn([settings.totalAmount])
)(state)
You see that we give most of these methods the state (state). I have added the compose
method as composeState
in the reducer action callback. That one already has the state so no need to provide it
SUCCESS: ( state, { composeState } ) {
return composeState(
updateIn(),
// ...
)
}