Skip to content

Instantly share code, notes, and snippets.

@sylvanaar
Last active December 31, 2020 11:01
Show Gist options
  • Save sylvanaar/60e87a61c4e3ec79dda9437def879664 to your computer and use it in GitHub Desktop.
Save sylvanaar/60e87a61c4e3ec79dda9437def879664 to your computer and use it in GitHub Desktop.
Generated by XState Viz: https://xstate.js.org/viz
// Available variables:
// - Machine
// - interpret
// - assign
// - send
// - sendParent
// - spawn
// - raise
// - actions
// - XState (all XState exports)
const oneSecTick = actions.send("TICK", {
delay: 1000,
id: "mainTimer",
});
const cancelTick = actions.cancel("mainTimer");
const fetchMachine = Machine(
{
id: "auth",
initial: "startup",
context: {
token: null,
promise: null,
expiration: null,
},
states: {
startup: {
on: {
"": [
{ target: "loggedIn", cond: "loggedIn" },
{ target: "loggedOut", cond: "loggedOut" },
],
},
},
requesting: {
on: {
RESOLVE: [
{ target: "loggedIn", action: actions.assign({ expiration: 10 }) },
],
REJECT: [
{ target: "loggedIn", cond: "loggedIn" },
{ target: "loggedOut", cond: "loggedOut" },
],
},
},
loggedIn: {
entry: [{ action: actions.assign({ expiration: 10 }) }, oneSecTick],
exit: cancelTick,
on: {
LOGOUT: "loggedOut",
TICK: [
{ target: "requesting", cond: "expired" },
{
action: actions.assign({
expiration: (context) => context.expiration - 1,
}),
},
],
},
},
loggedOut: {
entry: ["clearData"],
on: {
LOGIN: "requesting",
},
},
},
},
{
guards: {
loggedIn: (context, event) =>
context.token !== null && context.promise !== null,
loggedOut: (context, event) => context.token === null,
requesting: (context, event) => context.promise !== null,
expired: (context, event) => context.expiration <= 0,
},
actions: {
saveToken: (context, event) => {
context.token = event.data;
context.expiration = 10;
},
savePromise: (context, event) => (context.promise = event.data),
clearData: (context, event) => {
context.token = null;
context.promise = null;
},
},
}
);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment