Skip to content

Instantly share code, notes, and snippets.

@christiannwamba
Last active May 15, 2020 06:14
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save christiannwamba/ee37014fc2cebc56066ec1056407528e to your computer and use it in GitHub Desktop.
Save christiannwamba/ee37014fc2cebc56066ec1056407528e to your computer and use it in GitHub Desktop.
Generated by XState Viz: https://xstate.js.org/viz
// DEMO: Async and Promises
const fetchCuteAnimals = () => {
// Uncomment to test failure
// return Promise.reject()
return fetch('https://www.reddit.com/r/aww.json')
.then(res => res.json())
.then(data => data.data.children.map(child => child.data))
}
const fetchMachine = Machine({
id: 'cuteAnimals',
initial: 'idle',
context: {
cureAnimals: null,
error: null
},
states: {
idle: {
on: {
FETCH: 'loading'
}
},
loading: {
// instead of on,
// use invoke to
// invoke a promise
invoke: {
id: 'fetchCuteAnimals',
src: fetchCuteAnimals,
// Resolve
onDone: {
target: 'success',
actions: assign({
cureAnimals: (context, event) => event.data
})
},
// Reject
onError: {
target: 'failure',
actions: assign({
error: (context, event) => event.data
})
}
}
},
success: {
type: 'final'
},
failure: {
on: {
RETRY: 'loading'
}
}
}
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment