@xstate/immer
XState with Immer
This package contains utilities for using Immer with XState.
Quick start
Included in @xstate/immer
:
assign()
- an Immer action that allows you to immutably assign to machine context
in a convenient waycreateUpdater()
- a useful function that allows you to cohesively define a context update event event creator and assign action, all together. (See an example below)
- Install
immer
, xstate
, @xstate/immer
:
npm install immer xstate @xstate/immer
Note: You don't need to import
anything from immer
; it is a peer-dependency of @xstate/immer
, so it must be installed.
- Import the Immer utilities:
import { createMachine, interpret } from 'xstate';
import { assign, createUpdater } from '@xstate/immer';
const levelUpdater = createUpdater('UPDATE_LEVEL', (ctx, { input }) => {
ctx.level = input;
});
const toggleMachine = createMachine({
id: 'toggle',
context: {
count: 0,
level: 0
},
initial: 'inactive',
states: {
inactive: {
on: {
TOGGLE: {
target: 'active',
actions: assign((ctx) => ctx.count++)
}
}
},
active: {
on: {
TOGGLE: {
target: 'inactive'
},
[levelUpdater.type]: {
actions: levelUpdater.action
}
}
}
}
});
const toggleService = interpret(toggleMachine)
.onTransition((state) => {
console.log(state.context);
})
.start();
toggleService.send('TOGGLE');
toggleService.send(levelUpdater.update(9));
toggleService.send('TOGGLE');
toggleService.send(levelUpdater.update(-100));