Daskalo / Do you speak JavaScript? / Your JavaScript app is made of state machin...
source link: https://daskalo.dev/courses/do-you-speak-javascript/13
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.
§ Your JavaScript app is made of state machines
In this video, we will introduce the concept of state machines in JavaScript and how they can be used to model and manage the state of an object or system.
A state machine is a mathematical model of computation that describes the behavior of a system as a sequence of states, transitions between those states, and actions that are taken when entering or leaving a state. State machines can be used to model a wide range of systems, from simple programs to complex systems like traffic lights or vending machines.
Here's the example of the state machine that we implemented in the video lesson:
const IDLE = 'IDLE';
const LOADING = 'LOADING';
const SUCCESS = 'SUCCESS';
const ERROR = 'ERROR';
const state = {
currentState: IDLE,
products: null
};
const machine = {
[IDLE]: {
[LOADING]: async () => {
try {
state.products = await loadData();
machine.transitionTo(SUCCESS);
} catch(error) {
machine.transitionTo(ERROR);
}
}
},
[LOADING]: {
[SUCCESS]: () => {
render();
},
[ERROR]: () => {
render();
}
},
transitionTo(newState) {
if (machine[state.currentState][newState]) {
const func = machine[state.currentState][newState];
state.currentState = newState;
render();
func();
} else {
throw new Error(`${newState} doesn't make sense`);
}
}
}
There are a couple of important concepts while implementing such logic.
- We first define our states. In the example above those are
IDLE
,LOADING
,SUCCESS
andERROR
. - We define the possible transitions out of each of the states.
- We have a mechanism to perform a transition. (The
transitionTo
function).
Recommend
About Joyk
Aggregate valuable and interesting links.
Joyk means Joy of geeK