@immerx/state
v3.2.2
Published
Reactive & fractal state management with Immer
Downloads
8
Maintainers
Readme
Reactive and fractal state management with Immer
Table of contents:
Install
npm install @immerx/state
Immer >= v6.0.0
is a peer dependency so make sure it's installed.
Create
import create from '@immerx/state'
const state$ = create({ count: 0 })
Pretty simple - we create a new state by importing create
and call it with an initial state value.
Observe
import create from '@immerx/state'
const state$ = create({ count: 0 })
state$.subscribe({
next: v => console.log(`Count is: ${v}`),
})
// > Count is: 0
Our state$
is an observable which we can subscribe to and get notified on every state change.
Update
The following examples assume that you already know about Immer, what drafts & producers are and how to use them.
import create from '@immerx/state'
const state$ = create({ count: 0 })
state$.subscribe({
next: v => console.log(`Count is: ${v}`),
})
// > Count is: 0
state$.update(draft => void draft.count++)
// > Count is: 1
Our state$
exposes an update
method that takes a curried producer in order to update the underlying state object.
Compose
In addition to being reactive, state$
is also fractal, which allows as to create and compose smaller and isolated pieces of state where consumers will be notified only for relevant changes. Updates are also isolated so the consumer doesn't need to know anything about the "global" state:
import create from '@immerx/state'
const state$ = create({ parent: { child: { name: 'foo' } } })
const parentState$ = state$.isolate('parent')
const childState$ = parentState$.isolate('child')
parentState$.subscribe({
next: v => console.log('parent state: ', v),
})
// > parent state: { child: { name: "foo" } }
childState$.subscribe({
next: v => console.log('child state: ', v),
})
// > child state: { name: "foo" }
state$.update(draft => void (draft.otherParent = {}))
/* nothing logged after this update */
parentState$.update(parentDraft => void (parentDraft.sibling = 'bar'))
// > parent state: { child: { name: "foo" }, sibling: "bar" }
childState$.update(() => 'baz')
// > parent state: { child: { name: "baz" }, sibling: "bar" }
// > child state: { name: "baz" }
Combine and compute
More often than we'd like, our consumers need to combine and/or compute different pieces of state, sometimes including parts of its parent state. This type of isolation can be achieved through lenses
.
Lenses allow you to abstract state shape behind getters and setters.
import create from '@immerx/state'
const INITIAL_STATE = {
user: { name: 'John', remainingTodos: [1, 2] },
todos: ['Learn JS', 'Try immerx', 'Read a book', 'Buy milk'],
}
const state$ = create(INITIAL_STATE)
const user$ = state$.isolate({
get: state => ({
...state.user,
remainingTodos: state.user.remainingTodos.map(idx => state.todos[idx]),
}),
set: (stateDraft, userState) => {
const idxs = userState.remainingTodos.map(t => {
const idx = stateDraft.todos.indexOf(t)
return idx > -1 ? idx : stateDraft.todos.push(t) - 1
})
stateDraft.user = { ...userState, remainingTodos: idxs }
},
})
user$.subscribe({
next: console.log,
})
// > { name: "John", remainingTodos: [ "Try immerx", "Read a book" ] }
user$.update(userDraft => void userDraft.remainingTodos.push('Say hello'))
// > { name: "John", remainingTodos: [ "Try immerx", "Read a book", "Say hello" ] }
user$.update(userDraft => void userDraft.remainingTodos.splice(1, 1))
// > { name: "John", remainingTodos: [ "Try immerx", "Say hello" ] }
Let's quickly explain what's going on here:
Obviously, it's a very simple todos app where the state seems to have a normalized shape. We use a lens to provide our consumer with an isolated piece of the state (user$
) where the getter
returns the user
object but also expands user.remainingTodos
.
get: state => ({
...state.user,
remainingTodos: state.user.remainingTodos.map(idx => state.todos[idx]),
})
The consumer can manipulate the remainingTodos
without having any idea that a todos
list exists in the parent state and that user.remainingTodos
is actually a list of pointers to entries inside todos
.
It can safely push the todo text inside the remainingTodos
:
user$.update(userDraft => void userDraft.remainingTodos.push('Say hello'))
The lens' setter
will take care of updating the parent state while keeping it normalized.
set: (stateDraft, userState) => {
const idxs = userState.remainingTodos.map(t => {
const idx = stateDraft.todos.indexOf(t)
return idx > -1 ? idx : stateDraft.todos.push(t) - 1
})
stateDraft.user.remainingTodos = idxs
}
Middleware
Middleware implementations are based around immer patches. We can register functions (middleware) with immerx and they will receive a reference to the state$
and then be invoked with every patch. Based on how and where something was updated in our state, our middleware can perform side-effect and/or update the state.
The middleware signature is very simple:
function middleware(state$) {
return ({ patches, inversePatches }, state) => {
/**
* This function is called for every state update.
*
* It receives the list of patches/inversePatches
* and is closed over the state$ so we can use state$.update()
* to update the state in response
*/
}
}
We can now pass our middleware to create
and it'll be registered with immerx
import create from '@immerx/state'
import initialState from './state'
import middleware from './middleware'
create(initialState, [middleware])
Check out @immerx/observable - an observable based middleware.
Use with React
Check out the React bindings at @immerx/react
Developer tools
The @immerx/devtools component provides an overview of all the state changes.
There is a Chrome Devtools extension available but it can also be rendered inline, either manually by using the exported React component, or as part of an iframe if you're not using React.