5 ms·
JavaScript has libraries for this (xstate) but I usually just do it something like this in typescript: enum State { A, B, C }; enum Action { A, B };
by presentation 4y ago
JavaScript has libraries for this (xstate) but I usually just do it something like this in typescript:
enum State { A, B, C };
enum Action { A, B };
type StateData =
| { state: State.A, data: whatever }
| { state: State.B, data: whatever }
| { state: State.C, data: whatever };
type ActionData =
| { type: Action.A, data: whatever }
| { type: Action.B, data: whatever };
function transition(prev: StateData, action: ActionData): StateData {
switch(action.type) {
case Action.A:
return { type: State.B, data: whatever };
case Action.B:
return { type: State.C, data: whatever };
}
}
Then you can for example if you were using this in react do something like
function MyComponent() {
const [state, setState] = useState<StateData>({ state: State.A, data: whatever });
return <button onClick={() => setState(transition(state, { action: Action.A, data: whatever }))}>Go!</button>;
}