Skip to content

Instantly share code, notes, and snippets.

@drejohnson
Created January 1, 2021 00:31
Show Gist options
  • Save drejohnson/d6ff82921502d4608b8776bdc267711a to your computer and use it in GitHub Desktop.
Save drejohnson/d6ff82921502d4608b8776bdc267711a 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 fetchMachine = Machine({
id: 'authentication',
initial: 'authenticating',
context: {
auth: undefined,
user: undefined,
error: undefined,
},
states: {
authenticating: {
invoke: {
id: 'authChecker',
src: 'authChecker',
onDone: { target: 'loading', actions: 'setAuth' },
onError: { target: 'loggedOut' },
},
},
// we will enrich the user profile
// with additional data
loading: {
invoke: {
id: 'loader',
src: 'loader',
onDone: {
target: 'loggedIn',
actions: 'setUser',
},
onError: {
target: 'loggedOut.failed',
actions: ['setError', 'clearAuth'],
},
},
},
loggedIn: {
// when receiving 'LOGOUT' event
// transition to singingOut state
on: { LOGOUT: { target: 'loggingOut' } },
},
// loggedOut has two sub-states
// we will transition to failed in
// case of wrong password, username
// or network error
loggedOut: {
initial: 'ok',
states: {
ok: { type: 'final' },
failed: {},
},
on: {
LOGIN: { target: 'loggingIn' },
REGISTER: { target: 'creatingUser' },
},
},
loggingIn: {
invoke: {
id: 'authenticator',
src: 'authenticator',
onDone: {
target: 'authenticating',
// clear error if successful login
actions: 'clearError',
},
onError: {
// transition to failed state
// and set an error
target: 'loggedOut.failed',
actions: 'setError',
},
},
},
creatingUser: {
invoke: {
id: 'createUser',
src: 'createUser',
onDone: {
target: 'authenticating',
// clear error if successful login
actions: 'clearError',
},
onError: {
// transition to failed state
// and set an error
target: 'loggedOut.failed',
actions: 'setError',
},
},
},
loggingOut: {
invoke: {
id: 'logout',
src: 'logout',
onDone: {
target: 'loggedOut',
actions: ['clearAuth', 'clearError'],
},
onError: {
target: 'loggedOut.failed',
actions: ['clearAuth', 'setError'],
},
},
},
},
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment