Created
December 31, 2020 11:01
-
-
Save sylvanaar/05c2500ba5e5f4ec131aef4a7a19ade0 to your computer and use it in GitHub Desktop.
Generated by XState Viz: https://xstate.js.org/viz
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 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