Last active
October 29, 2019 20:38
-
-
Save itsMapleLeaf/33b665b594ec5c6c564ca8b46cbbff87 to your computer and use it in GitHub Desktop.
root store hook example
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
| // in RootStore.ts | |
| export class RootStore { | |
| userStore = new UserStore() | |
| chatStore = new ChatStore() | |
| appNavigationStore = new AppNavigationStore() | |
| } | |
| export const RootStoreContext = React.createContext<RootStore>() | |
| export function useRootStore() { | |
| const store = React.useContext(RootStoreContext) | |
| if (!store) { | |
| throw new Error( | |
| "useRootStore() can only be used inside the RootStoreContext provider", | |
| ) | |
| } | |
| return store | |
| } | |
| // in index | |
| ReactDOM.render( | |
| <RootStoreContext.Provider value={new RootStore()}> | |
| <App /> | |
| </RootStoreContext.Provider>, | |
| document.getElementById("root"), | |
| ) | |
| // in components | |
| function UserProfile({ userId }: { userId: string }) { | |
| const { userStore } = useRootStore() | |
| const user = userStore.getUser(userId) | |
| return ( | |
| <main> | |
| <h1>{user.name}</h1> | |
| <p>{user.bio}</p> | |
| </main> | |
| ) | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment