Skip to content

Instantly share code, notes, and snippets.

@hitrik
Created April 27, 2021 20:58
Show Gist options
  • Save hitrik/104d8c24143588dc143d79a8f794777d to your computer and use it in GitHub Desktop.
Save hitrik/104d8c24143588dc143d79a8f794777d 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 getLocalStoreUser = () => new Promise((res, rej) => setTimeout(res({name: 'Vasya'}), 2000));
const createUser = (name) => ({
name: name + ' Ustinov',
age: 19,
hobby: 'reading'
})
const getUserMachine = Machine({
id: 'user-local',
initial: 'idle',
context: {
user: null,
error: false
},
states: {
idle: {
on: {
'SYNC': 'synchronize',
delay: 1800
}
},
synchronize: {
invoke: {
id: 'getLocalUser',
src: () => getLocalStoreUser(),
onDone: {
target: 'success',
actions: assign({ user: (_, event) => event.data })
},
onError: {
target: 'failure'
}
},
},
success: {
on: {
'GET_LOCAL_USER': [
{
actions: send('LOCAL_USER_EXISTS', {to: 'call'}),
cond: 'localUserExists'
},
{
actions: 'sendUser'
}
]
},
type: 'final'
},
failure: {
entry: 'sendUser'
}
}
}, {
actions: {
sendUser: () => send('LOCAL_USER_EMPTY', {to: 'call'})
},
guards: {
localUserExists: ctx => ctx.user != null
}
});
const callMachine = Machine({
id: 'call',
initial: 'idle',
context: {
user: null
},
states: {
idle: {
on: {
'START': 'active'
}
},
active: {
invoke: {
id: 'callUserMachine',
src: getUserMachine,
onDone: {
target: 'ready'
}
},
},
ready: {
on: {
'LOCAL_USER_EXISTS': {
actions: (ctx) => assign({
user: () => createUser('Vasyaka')
})
}
}
}
}
})
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment