Skip to content

Instantly share code, notes, and snippets.

@vuhrmeister
Created September 3, 2019 14:43
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save vuhrmeister/8650e59253bbd61579c51be1f9065c1a to your computer and use it in GitHub Desktop.
Save vuhrmeister/8650e59253bbd61579c51be1f9065c1a to your computer and use it in GitHub Desktop.
Generated by XState Viz: https://xstate.js.org/viz
const fetchRoute = () => {
return new Promise((resolve, reject) => {
resolve({
stops: [{ id: 1 }, { id: 2 }]
})
})
}
const stopMachine = Machine({
id: 'stop',
initial: 'idle',
context: {
id: undefined
},
states: {
idle: {
},
started: {
onEntry: sendParent(ctx => ({ type: 'STOP_STARTED', stopId: ctx.id }))
},
completed: {
type: 'final',
onEntry: sendParent(ctx => ({ type: 'STOP_COMPLETED', stopId: ctx.id }))
}
}
})
const routeMachine = Machine({
id: 'route',
initial: 'loadRoute',
context: {
activeStop: null,
stops: []
},
states: {
loadRoute: {
invoke: {
src: fetchRoute,
onDone: {
target: 'initializingStops',
actions: assign((ctx, evt) => ({
...evt.data
}))
}
}
},
initializingStops: {
onEntry: 'initializeStops',
on: {
'': 'started'
}
},
started: {
on: {
STOP_STARTED: {
target: '',
actions: 'setActiveStop'
},
STOP_COMPLETED: {
target: '',
actions: 'unsetActiveStop'
}
}
},
done: {
type: 'final'
}
}
}, {
actions: {
initializeStops: assign({
stops: ctx => ctx.stops.map((stop, routeIndex) => ({
...stop,
ref: spawn(stopMachine.withContext({ ...stop, routeIndex }))
}))
}),
setActiveStop: assign({
activeStopId: (ctx, evt) => evt.stopId || null
}),
unsetActiveStop: assign({
activeStopId: (ctx, evt) => null
})
}
})
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment