Skip to content

Instantly share code, notes, and snippets.

@xralphack
Last active February 25, 2021 04:18
Show Gist options
  • Select an option

  • Save xralphack/23a12a3034ad319138febe0e9eb23f19 to your computer and use it in GitHub Desktop.

Select an option

Save xralphack/23a12a3034ad319138febe0e9eb23f19 to your computer and use it in GitHub Desktop.
Generated by XState Viz: https://xstate.js.org/viz
const fetchDeviceState = () =>
Math.random() > 0.8 ? Promise.resolve() : Promise.reject()
const yardianStateMachine = Machine({
id: 'yardian-state-machine',
initial: 'fetchingDeviceState',
context: {
retries: 0
},
states: {
fetchingDeviceState: {
entry: ['incrementRetries'],
invoke: {
id: 'fetchDeviceState',
src: fetchDeviceState,
onDone: {
target: 'success'
},
onError: {
target: 'failure'
}
}
// on: {
// success: {
// target: 'success'
// },
// failure: {
// target: 'failure'
// }
// }
},
success: {
entry: ['resetRetries', 'parseDeviceState'],
states: {
watering: {
}
}
},
failure: {
on: {
'': {
target: "fatal",
cond: (context) => context.retries >= 3
}
},
after: {
1000: {
target: 'fetchingDeviceState',
}
}
},
fatal: {
on: {
RETRY: {
target: 'fetchingDeviceState',
actions: ['resetRetries']
}
}
}
}
}, {
actions: {
'incrementRetries': assign({ retries: context => context.retries + 1 }),
'resetRetries': assign({ retries: 0 }),
parseDeviceState: (context, event) => {
console.log(event.data);
}
}
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment