Skip to content

Instantly share code, notes, and snippets.

@k-sav
Last active March 20, 2020 00:27
Show Gist options
  • Save k-sav/d14458ca74d0e760133fb98eba6b9d27 to your computer and use it in GitHub Desktop.
Save k-sav/d14458ca74d0e760133fb98eba6b9d27 to your computer and use it in GitHub Desktop.
Generated by XState Viz: https://xstate.js.org/viz
const authMachine = Machine(
{
id: 'authentication',
initial: 'unauthorized',
context: {
errorMessage: null,
user: null,
email: '',
password: '',
},
states: {
unauthorized: {
on: {
LOGIN: 'loading',
SET_EMAIL: {actions: ['changeEmail']},
SET_PASSWORD: {actions: ['changePassword']},
},
},
loading: {
invoke: {
id: 'getUser',
src: (context, event) => fetchUser(context.email, context.password),
onDone: {
target: 'authorized',
actions: assign({user: (context, event) => event.data}),
},
onError: {
target: 'unauthorized',
actions: assign({errorMessage: (context, event) => event.data}),
},
},
},
authorized: {
on: {
LOGOUT: 'unauthorized',
},
initial: 'devices_loading',
context: {devices: [], interval: 5000},
states: {
devices_loading: {
invoke: {
id: 'getDevices',
src: (context, event) => fetchDevices,
onDone: {
target: 'devices_waiting',
actions: assign({
devices: (context, event) => event.data.devices,
}),
},
onError: {
target: 'devices_waiting',
},
},
},
devices_waiting: {
after: {
// TODO: Fix this
// https://xstate.js.org/docs/guides/delays.html#delayed-transitions
// after 5 seconds, transition to devices_loading
5000: {target: 'devices_loading'},
},
},
},
},
},
},
{
actions: {
onSuccess: (context, event) => {
context.user = event.user
context.errorMessage = null
},
onError: (context, event) => {
context.errorMessage = event.errorMessage
},
changeEmail: (context, event) => {
context.email = event.value
},
changePassword: (context, event) => {
context.password = event.value
},
},
},
)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment