0 day streak
javascript / expert
Snippet

Reactive Finite State Machines (FSM) in Composition API

Using a Finite State Machine pattern within Vue's Composition API prevents 'impossible states'. Instead of juggling multiple booleans like isLoading and isError, you define a single reactive state source and explicit transitions, making complex UI flows predictable and easier to debug.

snippet.js
javascript
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
const state = ref('IDLE');
const machine = {
IDLE: { START: 'LOADING' },
LOADING: { SUCCESS: 'SUCCESS', FAILURE: 'ERROR' },
ERROR: { RETRY: 'LOADING' },
SUCCESS: { RESET: 'IDLE' }
};
function send(event) {
const nextState = machine[state.value]?.[event];
if (nextState) {
state.value = nextState;
}
}
// Usage: send('START');
vue
Breakdown
1
const state = ref('IDLE');
The single source of truth for the current state of the component.
2
const machine = { ... };
Defines the strictly allowed transitions between states to prevent logic errors.
3
state.value = nextState;
Reactive update that triggers UI changes based on the new valid state.