immutable-modify
Slim zero dependencies helper function for modifying redux state or frozen objects
Easily create updated version of your Plain Javascript Object.
Function will create new references to objects or arrays when nested data is changed and leave references otherwise.
That allows react
and react-redux
to fast check your props using reference equality.
Analogs
Install
yarn add immutable-modify
or
npm install --save immutable-modify
Api
set(object, keyPath, value)
Arguments:
- object (Object): The object modify
- keyPath (string | Array): The path of the property to set
- value (any | (leaf) => any): The value to set or update function
Returns:
(Object): Returns object
import {set} from 'immutable-modify'
const state = {user: {name: 'Skywalker'}}
const newState = set(state, 'user.name', 'Dart Vader')
newState === state
newState.user === state.user
Also value
could be function:
import {set} from 'immutable-modify'
const state = {user: {name: 'Skywalker', isJedi: false}, settings: {}}
const newState = set(state, 'user.isJedi', (isJedi) => !isJedi)
newState === state
newState.user === state.user
newState.settings === state.settings
Attention!
That updater function should return new reference, otherwise nothing will updated:
import {set} from 'immutable-modify'
const state = {user: {name: 'Skywalker', isJedi: false}, settings: {}}
const newState = set(state, 'user', user => {
user.isJedi = true
return user
})
newState === state
newState.user === state.user
newState.settings === state.settings
push(object, path, item)
import {push} from 'immutable-modify'
const state = {sequence: [{a: 1}, {a: 2}]}
const newState = push(state, 'sequence', {a: 3})
newState === state
newState.sequence === state.sequence
newState.sequence[0] === state.sequence[0]
newState.sequence[1] === state.sequence[1]
merge(object, path, item)
import {merge} from 'immutable-modify'
const state = {product: {name: 'sepulka'}}
const newState = merge(state, 'product', {description: 'Best with sepulator'})
newState === state
newState.product === state.product
newState.product.name === state.product.name
remove(object, path)
import {remove} from 'immutable-modify'
const state = {product: {name: 'sepulka', isAvailable: true}}
const newState = remove(state, 'product.isAvailable')
newState === state
newState.product === state.product
Test
yarn test