Skip to content

Instantly share code, notes, and snippets.

@johnsonjo4531
Last active November 25, 2020 19:58
Show Gist options
  • Save johnsonjo4531/9ebbb04210124eb48f55fb9723601fcf to your computer and use it in GitHub Desktop.
Save johnsonjo4531/9ebbb04210124eb48f55fb9723601fcf to your computer and use it in GitHub Desktop.
Generated by XState Viz: https://xstate.js.org/viz
function canTraverse (graph, start, end) {
return Boolean(graph[start]?.[end]);
}
const questionsMachine = Machine({
id: "questions",
parallel: true,
context: {
routes: {
home: {
feed: true
},
},
// history stack with initial route of one
stack: ["home"]
},
states: {
app: {
initial: "home",
states: {
home: {},
feed: {}
}
},
router: {
on: {
ROUTER_SEND_TO: {
actions: assign((ctx, e) => {
const {stack} = ctx;
if(!e.route || !canTraverse(ctx.routes, ctx.stack[ctx.stack.length - 1], e.route)) {
return {
stack
}
}
return {
stack: stack.concat(e.route)
}
})
},
ROUTER_BACK: {
actions: assign(ctx => {
const { stack } = ctx;
const newStack = stack.slice(0, stack.length - 1);
const prev = stack[stack.length - 1];
if(newStack.length === 0) {
return {
stack
}
}
return {
stack: newStack
};
}),
cond: ctx => ctx.stack.length > 1
},
// ...
}
},
// ...
}
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment