Skip to content

Instantly share code, notes, and snippets.

@pckilgore
Last active March 10, 2021 00:07
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 pckilgore/c672dc4b9ef60f7bd4737bec5a93b7da to your computer and use it in GitHub Desktop.
Save pckilgore/c672dc4b9ef60f7bd4737bec5a93b7da 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 timerMachine = Machine({
id: 'timer',
initial: 'ready', // should be entry
context: {
accumulatedTime: 0,
start: null
},
states: {
running: {
on: {
STOP: {
target: 'stopped',
actions: [
assign({
accumulatedTime: (ctx) =>
ctx.accumulatedTime + (new Date() - ctx.start),
})
]
},
}
},
stopped: {
on: {
START: {
target: 'running',
actions: assign({
start: () => new Date(),
})
},
RESET: {
target: 'saveTime',
}
}
},
saveTime: {
invoke: {
id: 'save',
src: 'saveTimeAsync',
onDone: {
target: 'ready',
},
onError: {
target: 'stopped'
}
}
},
ready: {
on: {
START: {
target: 'running',
actions: [
assign(ctx => ({
accumulatedTime: 0,
start: new Date(),
}))
]
}
}
}
},
}, {
services: {
// simulate asyncStorage effect
saveTimeAsync: ctx => new Promise(res => {
setTimeout(() => {
const time = Math.round(ctx.accumulatedTime / 10000 / 60) * 10 ;
console.log(`Your end time was ${time} minutes`);
res();
}, 1000)
})
}
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment