Skip to content

Instantly share code, notes, and snippets.

@skkim7821
Created October 8, 2020 08:26
Show Gist options
  • Save skkim7821/72bb0ed84eefc0933f05c6e237b0ab46 to your computer and use it in GitHub Desktop.
Save skkim7821/72bb0ed84eefc0933f05c6e237b0ab46 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 fetching = () =>
fetch('https://hacker-news.firebaseio.com/v0/item/160705.json?print=pretty')
.then((res) => res.data)
const fetchMachine = Machine(
{
id: 'fetch',
initial: 'idle',
context: {
data: {},
error: {},
isFetching: false,
},
states: {
idle: {
entry: 'isNotFetching',
on: {
FETCH: 'fetching',
},
},
fetching: {
entry: 'isFetching',
invoke: {
id: 'repo',
src: fetching,
onDone: {
target: 'success',
actions: ['getData'],
},
onError: {
target: 'failure',
actions: ['getError'],
},
},
on: {
CANCEL: 'idle',
},
},
intervalFetching: {
after: {
INTERVAL: 'fetching',
},
on: {
CANCEL: 'idle',
},
},
success: {
entry: 'isNotFetching',
after: {
0: 'intervalFetching',
},
},
failure: {
entry: 'isNotFetching',
on: {
RETRY: 'idle',
},
},
},
},
{
delays: {
INTERVAL: 10000,
},
actions: {
getData: assign({
data: (context, event) => event.data,
}),
getError: assign({
error: (context, event) => event.data,
}),
isNotFetching: assign({ isFetching: false }),
isFetching: assign({ isFetching: true }),
},
},
)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment