statemachine
A statematchine allows you to wrap state with transitions. That means you can protect your logic from running in invalid states of the application.
Please read the statemachine guide to learn more about statemachines and typing them.

Create a statemachine

You define a whole namespace as a statemachine, you can have a nested statemachine or you can even put statemachines inside statemachines.
1
import { statemachine } from 'overmind'
2
3
export const machine = statemachine({
4
FOO: {
5
TOGGLE: () => ({ current: 'BAR' })
6
},
7
BAR: {
8
TOGGLE: () => ({ current: 'FOO' })
9
}
10
})
Copied!
You define a statemachine by setting up its states and what events to handle within each state. Each handler returns the new state of of the state machine.

Instantiate machine

You instantiate a machine by calinng its create method. This takes the initial state and any optional base state the lives across all states of the machine.
1
import { machine } from './myMachine'
2
3
export const state = {
4
myMachine: machine.create({ current: 'FOO' }, { list: [] })
5
}
Copied!

Transition between states

You transition the state machine by sending events.
That means you can send TOGGLE as an event to the machine. Think of sending events as actually changing the state, but in a controlled way. You can optionally pass a payload with the event.
1
export const toggle = ({ state, effects }) => {
2
state.myMachine.send('TOGGLE', somePayload)
3
}
Copied!

Matching state

In actions you can check what state a machine is in by using the matches API.
1
export const toggle = ({ state, effects }) => {
2
if (state.myMachine.matches('FOO')) {
3
state.myMachine.send('TOGGLE', 'Cool')
4
} else {
5
state.myMachine.send('TOGGLE', 'Not so cool')
6
}
7
}
Copied!
You can also directly use state.myMachine.current , but please read the guide to understand the different between these two ways of checking.
Last modified 5mo ago