3 easy steps to use xstate visualizer in Next.js


In this tutorial, we are going to focus on how to visualize your xstate machines in Next.js project
Step 1: install XState VSCode extension
To install it, navigate to your Next.js project home directory, and type in this command
code --install-extension statelyai.stately-vscode
This will install vscode state visualizer in your vscode editor.
If you have not created your Next.js project you can either visit my link to create it, or Next.js official documentation in this link
npm i xstate @xstate/react
##yarn
yarn add xstate @xstate/react
Next, we will create our state machine,
Create machine folder, and then create a file engine.js
import { createMachine, interpret } from 'xstate';
const engineMachine = createMachine({
id: 'Engine',
initial: 'idle',
states: {
idle: { on: { REV: 'active' } },
active: { on: { BRAKE: 'idle' } }
}
});
const engineService = interpret(engineMachine)
.onTransition((state) => console.log(state.value))
.start();
// => 'inactive'
toggleService.send('BRAKE');
// => 'active'
toggleService.send('REV');
// => 'idle'
This will create an engine machine, with an idle initial state.
If we pass in transition REV in state idle, we will be in state active
If we pass in transition BRAKE in state active, we will be in state idle.
Step 3 : visualize the state machine
Now , open engine.js file, and you will be able to see a gray hypertext right on top of createMachine (it is highlighted with yellow in the image below).
Click on it and you may be able to visualize your xstate machine.
Conclusion
We have seen how to install stately-vscode plugin in order to visualize xstate state transition diagram in visual studio code which enhance our understanding of the state machine of our system
If you love working with Next.js here is a link to browse Next.js topics like tables, loading spinners, charts