Skip to content

Instantly share code, notes, and snippets.

@sawyerh
Last active June 27, 2021 17:54
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save sawyerh/4d6ec283549256c22409bb4ac074c5b1 to your computer and use it in GitHub Desktop.
Save sawyerh/4d6ec283549256c22409bb4ac074c5b1 to your computer and use it in GitHub Desktop.
Machine - Routing using state machines
// machine.js
import { Machine } from "xstate";
// Conditions for some of our transitions
const guards = {
hasJobIncome: (context) => context.has_job_income === true,
};
export const routingMachine = Machine({
// Initial state is mostly useful for visualizations, for our purposes.
initial: routes.auth.login,
states: {
[routes.auth.login]: {
on: {
LOG_IN: routes.apply.start,
FORGOT_PASSWORD: routes.auth.reset,
},
},
[routes.auth.reset]: {
on: {
RESET: routes.auth.login,
},
},
[routes.apply.start]: {
on: {
CONTINUE: routes.apply.name,
},
},
[routes.apply.name]: {
on: {
CONTINUE: routes.apply.income,
},
},
[routes.apply.income]: {
on: {
CONTINUE: [
{
cond: "hasJobIncome",
target: routes.apply.documents,
},
// If the above condition isn't met, we route to this page instead:
{ target: routes.apply.review },
],
},
},
[routes.apply.documents]: {
on: {
CONTINUE: routes.apply.review,
},
},
[routes.apply.review]: {
on: {
CONTINUE: routes.apply.success,
},
},
[routes.apply.success]: {},
},
guards,
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment