Last active
February 13, 2021 19:03
-
-
Save hypeJunction/cd0abe49ac373973f004a84c0809f47a to your computer and use it in GitHub Desktop.
This file contains hidden or 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
| export function useMachineTransition (transitionName) { | |
| const { | |
| states, | |
| state, | |
| setState, | |
| context, | |
| setContext, | |
| } = useContext(StateMachineContext) | |
| return useAsyncCallback(async (payload = {}) => { | |
| const definition = states?.[state]?.[transitionName] | |
| if (typeof definition === 'undefined') { | |
| throw new Error(`Invalid transition ${transitionName} from ${state}`) | |
| } | |
| let snapshot = Object.freeze({ ...context }) | |
| const setSnapshot = (fn) => { | |
| snapshot = Object.freeze(fn(snapshot)) | |
| } | |
| await definition.handlers.reduce((prev, cur) => { | |
| return prev.then(() => cur({ | |
| context: snapshot, | |
| setContext: setSnapshot, | |
| }, payload)) | |
| }, Promise.resolve()) | |
| setState(definition.target) | |
| setContext({ ...snapshot }) | |
| }) | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment