Created
August 14, 2022 22:21
-
-
Save evgeniyPP/6d667408f4f1a8bce898eb3d519f4bad to your computer and use it in GitHub Desktop.
XState global state machine hook
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
import { createContext } from 'react'; | |
import { InterpreterFrom } from 'xstate'; | |
import { useInterpret } from '@xstate/react'; | |
import { someMachine } from './someMachine'; | |
export const GlobalStateContext = createContext({ someService: {} as InterpreterFrom<typeof someMachine> }); | |
export const GlobalStateProvider = (props: React.PropsWithChildren) => { | |
const someService = useInterpret(someMachine); | |
return ( | |
<GlobalStateContext.Provider value={{ someService }}> | |
{props.children} | |
</GlobalStateContext.Provider> | |
); | |
}; |
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
import { useContext } from 'react'; | |
import { useSelector } from '@xstate/react'; | |
import type { StateFrom } from 'xstate'; | |
import { GlobalStateContext } from '../GlobalStateProvider'; | |
import type { someMachine } from './someMachine'; | |
export function useSomeMachine() { | |
const context = useContext(GlobalStateContext); | |
function select<T>(cb: (state: StateFrom<typeof someMachine>) => T): T { | |
return useSelector(context.someService, cb); | |
} | |
return { select, send: context.someService.send }; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment