Last active
October 3, 2022 16:21
-
-
Save davidkpiano/69dde705f0db39b7860c1dc3ec6ac682 to your computer and use it in GitHub Desktop.
Generated by XState Viz: https://xstate.js.org/viz
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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