-
-
Save JamieMason/9d1b757b082d4b5e608787648a15bb7b to your computer and use it in GitHub Desktop.
xState service layer
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 React from "react"; | |
import { createUserSessionService } from "services/UserSessionService"; | |
import { createNavService } from "services/NavService"; | |
// Wiring up our "IOC container" | |
const userSessionService = createUserSessionService(); | |
// NavService depends on UserSessionService | |
const navService = createNavService(userSessionService); | |
const dependencies = { | |
userSessionService, | |
navService | |
}; | |
const AppContext = React.createContext(dependencies); | |
const AppContextProvider: React.FC = props => { | |
return ( | |
<AppContext.Provider value={dependencies}> | |
{props.children} | |
</AppContext.Provider> | |
); | |
}; | |
export { AppContext, AppContextProvider }; |
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 React from "react"; | |
import ReactDOM from "react-dom"; | |
import App from "App"; | |
import { AppContextProvider } from "AppContextProvider"; | |
// Wrapping our app in our "IOC container" | |
ReactDOM.render( | |
<AppContextProvider> | |
<App /> | |
</AppContextProvider>, | |
document.getElementById("root") | |
); |
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 { Machine, interpret, Interpreter } from "xstate"; | |
import { useService } from "@xstate/react"; | |
import { AppContext } from "AppContextProvider"; | |
import { config, UserSessionContext, UserSessionStateSchema, UserSessionEvent } from "./machine"; | |
// Custom hook for "dependency injection" | |
export const useUserSessionService = () => { | |
const { userSessionService } = useContext(AppContext); | |
return useService(userSessionService); | |
}; | |
export const createUserSessionService = (): UserSessionService => { | |
const userSessionMachine = Machine<UserSessionContext, UserSessionStateSchema, UserSessionEvent>(config); | |
return ( | |
interpret(userSessionMachine) | |
.start() | |
); | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment