Skip to content

Instantly share code, notes, and snippets.

@mr-mig
Last active November 22, 2019 12:47
Show Gist options
  • Save mr-mig/43e9d8859fcbcfdb8c0bf83d0873f4a6 to your computer and use it in GitHub Desktop.
Save mr-mig/43e9d8859fcbcfdb8c0bf83d0873f4a6 to your computer and use it in GitHub Desktop.
Generated by XState Viz: https://xstate.js.org/viz
// https://xstate.js.org/viz/?gist=43e9d8859fcbcfdb8c0bf83d0873f4a6
// Available variables:
// - Machine
// - interpret
// - assign
// - send
// - sendParent
// - spawn
// - raise
// - actions
// - XState (all XState exports)
const onlineMachine = Machine(
{
id: 'onlineChecker',
context: {
onlineCheckInterval: 30 * 1000,
remoteOnlineCheckURL:
'https://to-do-cdn.microsoft.com/static-assets/online.txt'
},
initial: 'init',
states: {
init: {
on: {
CHECK_REMOTE: '.checkingConnectivity'
},
invoke: {
src: 'offlineListener'
},
initial: 'checkingConnectivity',
states: {
checkingConnectivity: {
on: {
ONLINE: 'online',
OFFLINE: 'offline'
},
invoke: {
src: 'checkRemote',
onDone: 'online',
onError: {
actions: [send('OFFLINE'), sendParent('OFFLINE')]
}
},
},
online: {
entry: [sendParent('ONLINE')]
},
offline: {
on: {
ONLINE: 'online'
},
after: {
ONLINE_CHECK_INTERVAL: 'checkingConnectivity'
}
}
}
}
}
},
{
delays: {
ONLINE_CHECK_INTERVAL: ctx => ctx.onlineCheckInterval,
},
services: {
checkRemote: ctx => window.fetch(ctx.remoteOnlineCheckURL),
offlineListener: ctx => callback => {
const sendOnline = () => {
callback('ONLINE')
sendParent('ONLINE')
}
const sendOffline = () => {
callback('CHECK_REMOTE')
}
window.addEventListener('online', sendOnline)
window.addEventListener('offline', sendOffline)
return () => {
window.removeEventListener('online', sendOnline)
window.removeEventListener('offline', sendOffline)
}
}
}
}
)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment