Skip to content

Instantly share code, notes, and snippets.

@davidkpiano
Last active October 3, 2022 16:21
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save davidkpiano/69dde705f0db39b7860c1dc3ec6ac682 to your computer and use it in GitHub Desktop.
Save davidkpiano/69dde705f0db39b7860c1dc3ec6ac682 to your computer and use it in GitHub Desktop.
Generated by XState Viz: https://xstate.js.org/viz
const updatePosition = assign({
position: (_, event) => event.position,
})
function geoService(context, event) {
return cb => {
if (!navigator.geolocation) {
cb({
type: 'error',
error: new Error('Geolocation is not supported'),
})
return
}
const geoWatch = navigator.geolocation.watchPosition(
// sends back to parent
position => cb({type: 'success', position}),
error => cb({type: 'error', error}),
)
// disposal function
return () => navigator.geolocation.clearWatch(geoWatch)
}
}
Machine(
{
id: 'geo',
context: {
position: null,
},
initial: 'pending',
// invoke a service that lasts for the lifetime
// of this machine
invoke: {
src: 'geoService',
},
states: {
pending: {
initial: 'default',
states: {
default: {
after: {5000: 'timeout'},
},
timeout: {},
},
},
resolved: {},
rejected: {},
},
// lives on the root node because
// these can happen in any state
on: {
success: {
target: '.resolved',
actions: updatePosition,
},
error: {
target: '.rejected',
actions: updatePosition,
},
},
},
{
actions: {updatePosition},
services: {geoService}
},
)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment