Skip to content

Instantly share code, notes, and snippets.

@p-j
Created January 26, 2021 12:47
Show Gist options
  • Save p-j/1fac35ce7dbb623e8db5b964973dae65 to your computer and use it in GitHub Desktop.
Save p-j/1fac35ce7dbb623e8db5b964973dae65 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)
function sleep(ms) {
return new Promise(function (resolve) {
setTimeout(resolve, ms)
})
}
const fetchMachine = Machine({
id: 'timeslot machine',
initial: 'idle',
context: {
timeSlot: null,
attempt: 0,
maxAttempt: 3,
history: [],
},
states: {
idle: {
on: {
START: { target: 'sendingSMS', actions: 'history' },
FORCE: { target: 'timeSlotSelected', actions: 'history' },
},
},
sendingSMS: {
invoke: {
id: 'sendSMS',
src: async (context, event) => {
await sleep(1000)
if (Math.random() * 100 < 70) return Promise.reject('Failed SMS')
return Promise.resolve(true) // Success
},
onDone: { target: 'waitingForReply', actions: ['incrementAttempt', 'history'] },
onError: [
{
target: 'sendingSMS',
cond: (context) => context.attempt <= context.maxAttempt,
actions: ['incrementAttempt', 'history'],
},
{ target: 'selectingTimeSlot', actions: 'history' },
],
},
on: { CANCEL: { target: 'idle', actions: 'history' } },
},
waitingForReply: {
on: { TIMESLOT_SELECTED: { target: 'timeSlotSelected', actions: ['assignTimeSlot', 'history'] } },
},
selectingTimeSlot: {
on: { TIMESLOT_SELECTED: { target: 'timeSlotSelected', actions: ['assignTimeSlot', 'history'] } },
},
timeSlotSelected: { type: 'final' },
},
on: {
RESET: {
actions: ['reset'],
target: 'idle',
},
},
},{
actions: {
assignTimeSlot: assign({
timeSlot: (context, event) => {
console.log(event)
return event.data.timeSlot
},
}),
incrementAttempt: assign({
attempt: (context, event) => context.attempt + 1,
}),
history: assign({
history: (context, event) => [...context.history, event],
}),
reset: assign({
timeSlot: null,
attempt: 0,
maxAttempt: 3,
history: [],
}),
},
}
);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment