Navigation Menu

Skip to content

Instantly share code, notes, and snippets.

@cheton
Created May 21, 2020 14:58
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 cheton/ab3940fad3bb7658ec0095af37f9e4ee to your computer and use it in GitHub Desktop.
Save cheton/ab3940fad3bb7658ec0095af37f9e4ee to your computer and use it in GitHub Desktop.
Generated by XState Viz: https://xstate.js.org/viz
const fetchMachine = Machine({
id: 'fetchMachine',
initial: 'idle',
context: {
isFetchedOnce: false,
isFetching: false,
data: null,
error: null,
},
states: {
idle: {
on: {
FETCH: {
target: 'fetching',
actions: ['onFetching'],
},
},
},
fetching: {
invoke: {
src: 'fetch',
onDone: {
target: 'success',
actions: ['onSuccess'],
},
onError: {
target: 'failure',
actions: ['onFailure'],
},
},
},
success: {
on: {
FETCH: {
target: 'fetching',
actions: ['onClearData', 'onFetching'],
},
},
},
failure: {
on: {
FETCH: {
target: 'fetching',
actions: ['onClearData', 'onFetching'],
},
},
},
},
}, {
actions: {
onResetContext: assign((context, event) => ({ ...fetchMachine.initialState.context })),
onClearData: assign({
data: null,
error: null,
}),
onFetching: assign({
isFetching: true,
}),
onSuccess: assign({
isFetchedOnce: true,
isFetching: false,
data: (context, event) => event.data,
}),
onFailure: assign({
isFetching: false,
error: (context, event) => new Error(event.data?.message),
}),
},
services: {
fetch: (context) => null,
},
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment