Last active
January 9, 2021 04:06
-
-
Save sylvanaar/30b8cb512aede48a990b485363a5329d 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
const token = { | |
id: "token", | |
initial: "idle", | |
states: { | |
idle: { | |
initial: "unloaded", | |
states: { | |
unloaded: { | |
entry: [actions.send({ type: "UNLOADED", to: "#auth" })], | |
on: { | |
LOAD: "#token.loading", | |
}, | |
}, | |
prior: { | |
type: "history", | |
target: "unloaded", | |
}, | |
loaded: { | |
entry: actions.send({ type: "LOADED", to: "#auth" }), | |
on: { | |
EXPIRED: { target: "#token.loading" }, | |
"": { target: "#token.loading", cond: "expired" }, | |
}, | |
}, | |
}, | |
}, | |
loading: { | |
initial: "start", | |
on: { | |
UNLOAD: "#token.idle.unloaded", | |
OFFLINE: ".start" | |
}, | |
states: { | |
fetching: { | |
on: { | |
SUCCESS: { target: "#token.idle.loaded", actions: "setToken" }, | |
FAILED: "#token.idle", | |
}, | |
}, | |
start: { | |
on: { | |
"": { target: "fetching", cond: "online" }, | |
}, | |
}, | |
}, | |
}, | |
}, | |
}; | |
const auth = { | |
id: "auth", | |
initial: "loggedOut", | |
states: { | |
start: { | |
on: { | |
LOGIN: "loggedIn", | |
LOGOUT: "loggedOut", | |
}, | |
}, | |
loggedIn: { | |
on: { | |
UNLOADED: "loggedOut", | |
LOGOUT: { actions: actions.send({ type: "UNLOAD", to: "#token" }) }, | |
}, | |
}, | |
loggedOut: { | |
on: { | |
LOADED: "loggedIn", | |
LOGIN: { actions: actions.send({ type: "LOAD", to: "#token.idle" }) }, | |
}, | |
}, | |
}, | |
}; | |
const network = { | |
id: "network", | |
initial: "online", | |
states: { | |
start: { | |
on: { | |
NET_UP: "online", | |
NET_DOWN: "offline", | |
}, | |
}, | |
offline: { | |
entry: [actions.send({ type: "OFFLINE", to: "#token" }), actions.assign({ online: false })], | |
on: { | |
NET_UP: "online", | |
}, | |
}, | |
online: { | |
entry: [actions.send({ type: "ONLINE", to: "#token" }), actions.assign({ online: true })], | |
on: { | |
NET_DOWN: "offline", | |
}, | |
}, | |
}, | |
}; | |
const machine = Machine( | |
{ | |
id: "datapoints", | |
type: "parallel", | |
context: { | |
token: null, | |
expired: false, | |
promise: null, | |
expiresAt: 0, | |
online: false, | |
}, | |
states: { | |
auth, | |
network, | |
token, | |
}, | |
}, | |
{ | |
guards: { | |
expired: (context) => context.expired, | |
online: (context) => context.online, | |
}, | |
actions: { | |
clearToken: (context) => ({ | |
token: null | |
}), | |
setToken: (context, event) => ({ | |
token: (context) => event | |
}), | |
}, | |
}, | |
); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment