Skip to content

Instantly share code, notes, and snippets.

@ShenJack
Created March 8, 2021 06:36
Show Gist options
  • Save ShenJack/ec880882e0f9b3d31cd7c684fb013072 to your computer and use it in GitHub Desktop.
Save ShenJack/ec880882e0f9b3d31cd7c684fb013072 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)
function loadData() {
return new Promise((resolve, reject) => {
setTimeout(() => {
if (Math.random() > 0.5) {
resolve(
'Success \n\n' +
JSON.stringify({
code: 200,
data: {},
message: 'success',
}),
);
} else {
reject(
'Error \n\n' +
JSON.stringify({
code: 500,
data: {},
message: 'error',
}),
);
}
}, 500);
});
}
const fetchMachine = Machine({
id: 'dataLoadingMachine',
initial: 'idle',
context: {
data: undefined,
errorInfo: undefined,
},
states: {
idle: {
on: {
LOADING_START: 'loading',
},
},
loading: {
invoke: {
id: 'loadData',
src: loadData,
onDone: {
target: 'success',
actions: assign({ data: (context, event) => event.data }),
},
onError: {
target: 'error',
actions: assign({ errorInfo: (context, event) => event.data }),
},
},
},
success: {
on: {
LOADING_START: 'loading',
},
},
error: {
on: {
LOADING_START: 'loading',
},
},
},
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment