Skip to content

Instantly share code, notes, and snippets.

@horacioh
Created July 30, 2021 14:32
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 horacioh/4766e44e0835202e8d9ed52982a4c844 to your computer and use it in GitHub Desktop.
Save horacioh/4766e44e0835202e8d9ed52982a4c844 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 fetchMachine = Machine({
id: 'editor',
initial: 'idle',
context: {
retries: 0,
draft: null,
editorValue: null,
errorMessage: '',
},
states: {
idle: {
on: {
FETCH: {
target: 'fetching',
},
},
initial: 'noError',
states: {
noError: {
entry: ['clearErrorMessage'],
},
errored: {
on: {
FETCH: {
target: '#fetching',
actions: assign({
retries: (context, event) => context.retries + 1,
}),
},
},
},
},
},
fetching: {
id: 'fetching',
on: {
FETCH: 'fetching',
CANCEL: {
target: 'idle',
},
RECEIVE_DATA: {
target: 'editing',
actions: 'assignDataToContext',
},
},
invoke: {
src: 'fetchData',
onError: {
target: 'idle.errored',
actions: 'assignErrorToContext',
},
onDone: {
target: '#editing',
actions: 'assignDataToContext',
},
},
},
editing: {
id: 'editing',
initial: 'idle',
states: {
idle: {
on: {
UPDATE: {
actions: 'updateValueToContext',
target: 'debouncing',
},
PUBLISH: {
target: '#published',
},
},
},
debouncing: {
on: {
UPDATE: {
actions: 'updateValueToContext',
target: 'debouncing',
},
},
after: {
1000: {
target: 'idle',
actions: 'saveValue',
},
},
},
},
},
published: {
id: 'published',
type: 'final',
},
},
},
{
services: {
fetchData: (context, event) => () => ({
draft: {foo: 'bar', children: [{bar: 'baz'}]},
editorValue: [{bar: 'baz'}]
})
},
actions: {
updateValueToContext: assign((context, event) => {
return {
editorValue: event.value,
}
}),
saveValue: assign((context, event) => {
return {
draft: event.data,
editorValue: event.data,
}
}),
assignDataToContext: assign((context, event) => {
console.log('assignDataToContext', event.data)
if (event.type !== 'RECEIVE_DATA') return {}
return {
draft: event.data,
editorValue: event.data.children,
}
}),
clearErrorMessage: assign({
errorMessage: undefined,
}),
assignErrorToContext: assign((context, event) => {
console.log('assignErrorToContext', {context, event})
return {
errorMessage: event.data?.message || 'An unknown error occurred',
}
}),
},
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment