Skip to content

Instantly share code, notes, and snippets.

@hitrik
Last active May 1, 2021 17:12
Show Gist options
  • Save hitrik/b05e4a038edb84f23746a6448a115b66 to your computer and use it in GitHub Desktop.
Save hitrik/b05e4a038edb84f23746a6448a115b66 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 getUserFromLocalStorage = () => new Promise((res, rej) => setTimeout(() => res({
user: {
name: 'Vasya local',
age: 40
}
}), 2000));
const authUserWithServer = () => {
return new Promise((res, rej) => {
res({
name: 'Vasya online',
age: 40
})
})
}
const userMachine = Machine({
id: 'user',
initial: 'idle',
context: {
user: null,
error: ""
},
states: {
idle: {
on: {
'GET_USER': 'localAuth'
}
},
onlineAuth: {
},
localAuth: {
initial: 'get_local_user',
states: {
get_local_user: {
invoke: {
id: 'get_local_user',
src: () => getUserFromLocalStorage,
onDone: {
target: '#user.authorized',
actions: assign({
user: (_, event) => event.data
})
},
onError: {
target: 'failure',
actions: assign({
error: (_, event) => event.data
})
}
}
},
failure: {
on: {
'RETRY': 'get_local_user'
}
}
}
},
authorized: {
on: {
'CHECK': 'localAuth'
}
},
},
}, {
actions: {},
guards: {
localUserExists: (ctx) => false
}
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment