0 day streak
javascript / expert
Snippet

Type-Safe State Machines with Readonly

Managing UI state with loose booleans leads to 'impossible states'. Using a central reactive state machine combined with 'readonly' ensures that state transitions can only happen through dedicated methods, preventing external logic from corrupting the internal state.

snippet.js
javascript
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
import { ref, readonly, computed } from 'vue';
export function useAuthMachine() {
const state = ref('IDLE'); // IDLE | LOADING | AUTHENTICATED
const transition = (target) => {
const validTransitions = {
IDLE: ['LOADING'],
LOADING: ['AUTHENTICATED', 'IDLE'],
AUTHENTICATED: ['IDLE']
};
if (validTransitions[state.value].includes(target)) {
state.value = target;
}
};
return {
state: readonly(state),
isAuthenticated: computed(() => state.value === 'AUTHENTICATED'),
login: () => transition('LOADING'),
logout: () => transition('IDLE')
};
}
vue
Breakdown
1
state: readonly(state)
Exports a non-writable version of the state to the consumer.
2
validTransitions[state.value]
Logic check to ensure the state machine follows predefined rules.