Next lesson: Redux - the predictable state container To the next lesson →
Lesson: State machines Repeat
Do you speak JavaScript?
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.
IDLE
, LOADING
, SUCCESS
and ERROR
.transitionTo
function).Practice is the fastest way to learn knowledge permanently. I have prepared a small task for you related to the lesson.
Materials related to the lesson:
→ Files associated with the lesson