Introduction To XState
Introduction To XState
Introduction to XState
I wrote about finite state machines in the past and I mentioned XState. In
this post I want to introduce this popular JavaScript library.
Finite state machines are an interesting way to tackle complex state and
state changes and keep your code bugs-free as much as possible.
Computer programs are all about transitioning from one state to another after
an input. Things can get out of control if you're not paying close attention,
and XState is a very helpful tool to help us navigate the state complexity as
it grows.
then you can import it in your program using the ES Modules syntax. As a
minimum you typically import the Machine and interpret functions:
import { Machine, interpret } from 'xstate'
<script src="https://unpkg.com/xstate@4/dist/xstate.js"></script>
and this will make a global XState variable on the window object.
Next you can define a finite state machine using the Machine factory function.
This function accepts a configuration object, and returns a reference to the
newly created state machine:
})
},
yellow: {
},
red: {
}
}
})
Here I defined 3 states: green yellow and red .
Here we set to switch to the yellow state when we're in the green state and
we get a TIMER event:
},
red: {
}
}
})
I called it TIMER because traffic lights usually have a simple timer that
changes the lights state every X seconds.
Now let's fill the other 2 state transitions: we go from yellow to red, and
from red to green:
You can get the initial state string representation of the machine using:
and we can switch to a new state using the transition() method of machine (the
state machine instance returned by Machine() ):
You can store the new state object into a variable, and you can get its
string representation accessing the value property:
Using the transition() method you always have to keep track of the current
state, which in my mind causes a bit of pain. It'd be great if we could ask
the machine for its current state.
Now we can use this service send() method to retrieve the new state, without
having to pass the current state like we have to do with machine.transition() :
const toggleService = interpret(machine).start()
toggleService.send('TOGGLE')
We can store the return value, that will hold the new state:
Given a state, you can know what will trigger a state change using its
nextEvents property, that will return an array.
Yes, because from a state you can go to multiple states depending on the
trigger you get.
In the case of traffic lights, this is not something that will happen, but
let's model the house lights example we had in the finite state machines
post:
When you enter the house, you can press one of the 2 push buttons you have,
p1 or p2. When you press any of those buttons, the l1 light turns on.
Imagine this is the entrance light, and you can take your jacket off. Once
you are done, you decide which room you want to go into (kitchen or bedroom,
for example).
If you press the button p1, l1 turns off and l2 turns on. Instead if you
press the button p2, l1 turns off and l3 turns on.
Pressing another time any of the 2 buttons, p1 or p2, the light that is
currently on will turn off, and we’ll get back at the initial state of the
system.
See how now each state transition defined in the object passed to on instead
of being just a string it's an object with the target property (where we pass
the string we used before) and we also have an actions property where we can
set the action to run.
But in this case it's handy to put them all together because similar actions
are fired by different state transitions.
That's it for this tutorial. I recommend you to check out the XState Docs for
more advanced usage of XState, but it's a start.
I wrote 16 books for beginner software developers, you can download them all
now at 0.00₹ ($0) cost, all you need to do is subscribe to my newsletter.
Learn to code in THE VALLEY OF CODE, the learning platform for Web
Developers (in EARLY ACCESS right now)
Learn how to start a solopreneur business on the Internet with SOLO LAB
(next edition someday in 2024)
Find me on X
Related posts that talk about js:
» Change the color of a webpage dynamically using JS and CSS Nov 8, 2023
» How to ensure an image upload is smaller than a specific size Feb 16, 2023
» How to get retrieve all results of a regex with capturing Jan 14, 2023
groups in JS
» A regular expression to capture a URL without query string Jan 13, 2023
parameters
» How to fix an issue installing Node `canvas` on macOS May 18, 2022
» How to fix the "Parse failure: Unterminated string constant" May 9, 2022
error
» How to solve the document is not defined error May 4, 2022
» JavaScript, how to get the class name of an object Apr 29, 2022
» How to fix tsconfig.json "No inputs were found in config Apr 16, 2022
file" error
» How I built a dashboard for the iPad with JavaScript Nov 15, 2021
» How to copy the properties of an inner object to the outer Jul 20, 2021
» TypeScript, disable checks for `declared but its value is Jul 5, 2021
never read`
» How to solve the `TypeError: Attempted to assign to readonly May 12, 2021
property` error
» Johnny Five, receiving input from the device Apr 30, 2021
» Johnny Five, how to work with an LCD Screen Apr 28, 2021
JavaScript
» How to get the index of an item in a JavaScript array Aug 19, 2020
» Gatsby, fix the "cannot find module gatsby-cli/lib/reporter" Aug 15, 2020
error
» How to add an item at the beginning of an array in JavaScript Aug 11, 2020
» How I fixed a "cb.apply is not a function" error while using Aug 10, 2020
Gitbook
» Event delegation in the browser using vanilla JavaScript Jun 24, 2020
» The importance of timing when working with the DOM Jun 19, 2020
» How to change commas into dots with JavaScript Jun 18, 2020
» What are the ways we can break out of a loop in JavaScript? Jun 13, 2020
» What's the difference between a method and a function? Jun 12, 2020
» What is the difference between null and undefined in Jun 11, 2020
JavaScript?
» In which ways can we access the value of a property of an Jun 10, 2020
object?
» How can you tell what type a value is, in JavaScript? Jun 6, 2020
false
» How to get the last segment of a path or URL using JavaScript May 28, 2020
error
» How to solve the "is not a function" error in JavaScript May 1, 2020
» How to fix the TypeError: Cannot assign to read only property Apr 23, 2020
» How to remove the first character of a string in JavaScript Apr 21, 2020
» How to remove the last character of a string in JavaScript Apr 20, 2020
» The same POST API call in various JavaScript libraries Apr 8, 2020
» How to remove all the node_modules folders content Mar 11, 2020
» How to send the authorization header using Axios Jan 18, 2020
JavaScript
» How to get the days between 2 dates in JavaScript Oct 26, 2019
» How to wait for 2 or more promises to resolve in JavaScript Oct 25, 2019
» How to check if a date refers to a day in the past in Oct 16, 2019
JavaScript
» How to check if two dates are the same day in JavaScript Oct 12, 2019
» How to get the month name from a JavaScript date Oct 11, 2019
» What's the difference between using let and var in Sep 20, 2019
JavaScript?
» Why you should not modify a JavaScript object prototype Sep 14, 2019
» How to add item to an array at a specific index in JavaScript Sep 13, 2019
JavaScript
difference?
» How to check if a JavaScript array contains a specific value Aug 29, 2019
» How to check types in JavaScript without using TypeScript Aug 26, 2019
» How to rename fields when using object destructuring Aug 24, 2019
JavaScript
» How to solve the unexpected identifier error when importing Jan 31, 2019
modules in JavaScript
» The node_modules folder size is not a problem. It's a Jan 30, 2019
privilege
Expressions
» Work with objects and arrays using Rest and Spread Jan 3, 2019
JavaScript
» How to hide a DOM element using plain JavaScript Nov 20, 2018
JavaScript
» How to generate a random number between two numbers in Oct 20, 2018
JavaScript
» How to use Async and Await with Array.prototype.map() Oct 11, 2018
» How to check if a string starts with another in JavaScript Sep 29, 2018
» How to get the unique properties of a set of objects in a Sep 28, 2018
JavaScript array
» How to validate an email address in JavaScript Sep 27, 2018
» Write JavaScript loops using map, filter, reduce and find Apr 13, 2018
» How to upload files to the server using JavaScript Oct 25, 2013