Last active
July 30, 2021 09:16
-
-
Save horacioh/0597098ea7d1e29dc78416b63f5a5b82 to your computer and use it in GitHub Desktop.
Generated by XState Viz: https://xstate.js.org/viz
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// Available variables: | |
// - Machine | |
// - interpret | |
// - assign | |
// - send | |
// - sendParent | |
// - spawn | |
// - raise | |
// - actions | |
// - XState (all XState exports) | |
const fetchMachine = Machine({ | |
id: 'editor', | |
initial: 'idle', | |
context: { | |
retries: 0, | |
localState: {}, | |
prevSaved: {} | |
}, | |
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' | |
} | |
} | |
}, | |
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: () => () => {} | |
}, | |
actions: { | |
updateValueToContext: assign((context, event) => { | |
return { | |
localState: event.value | |
} | |
}), | |
saveValue: assign((context, event) => { | |
return { | |
localState: event.payload, | |
savedState: event.payload | |
} | |
}), | |
assignDataToContext: assign((context, event) => { | |
if (event.type !== 'RECEIVE_DATA') return {}; | |
return { | |
data: event.data, | |
}; | |
}), | |
clearErrorMessage: assign({ | |
errorMessage: undefined, | |
}), | |
assignErrorToContext: assign((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