One of my favorite uses of XState is for global state management.
It excels in an environment fully controlled by JavaScript, like a SPA (Single Page Application) or React Native.
This state machine is better suitable for this use case where you must control everything happening,
including the HTTP requests made to your authentication API.
Example
Loading user data
Inspect the demo in Stately Inspector
Restart the machine from the beginning
The state machine first checks if the user is initially authenticated.
In a real-world application, you would request a /me endpoint or authentication third-party service here.
The machine redirects the user to the screen matching her authentication state.
The machine stores the user’s data in the context of the machine after having retrieved them from the external API.
If the user is not initially authenticated, the machine redirects her to the sign-in screen,
where she can go to the sign-up screen.
When the user submits the sign-in or the sign-up form, the machine requests the auth API and expects it
to return whether the operation succeeded and, optionally, an error code or the user’s data. These data are stored
in the context of the machine to be used in the UI part.
An authenticated user can sign out from the website. The machine will make another request to the auth API to invalidate
the authentication token, and it will clear the user’s data. The machine will also redirect the user back to the sign-in screen.
Error handling is crucial in this scenario. In case of an error during signing-in or signing-up, an alert is displayed
with the error in a human-readable format. Promise actors can throw errors; the machine handles them thanks to the onError transitions.
Sign up for the newsletter to be notified when more machines or an
interactive tutorial are released. I respect your privacy and will
only send emails once in a while.