Created
July 30, 2020 06:11
-
-
Save cassidoo/4239c2fc1d9bed44941166637c3c7651 to your computer and use it in GitHub Desktop.
An example of component-izing context
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
//////// Some App file that uses the things we made | |
import React from "react" | |
import { LoggedIn, LoggedOut } from "app/thingies" | |
import { AppStateProvider } from "app/app-state" | |
import appReducer, { initialState } from "app/appReducer" | |
function App() { | |
const { authAttempted, auth } = useAuth() | |
return <div className="Layout">{auth ? <LoggedIn /> : <LoggedOut />}</div> | |
} | |
export default () => ( | |
<AppStateProvider reducer={appReducer} initialState={initialState}> | |
<App /> {/* So everything inside of <App /> can use the app reducer and the defined state for this context */} | |
</AppStateProvider> | |
) | |
//////// Our context file | |
import React, { createContext, useReducer, useContext } from "react" | |
const Context = createContext() | |
export function AppStateProvider({ reducer, initialState = {}, children }) { | |
const value = useReducer(reducer, initialState) | |
return <Context.Provider value={value} children={children} /> | |
} | |
export function useAppState() { | |
return useContext(Context) | |
} | |
//////// Our reducer file | |
const initialState = { user: null, something: 'what' } | |
const appStateReducer = (state, action) => { | |
switch (action.type) { | |
case "AUTH_CHANGE": { | |
return { ...state, user: action.user } | |
} | |
case "DO_SOMETHING": { | |
return { ...state, something: 'how' } | |
} | |
default: | |
return state | |
} | |
} | |
export { initialState } | |
export default appStateReducer |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment