Created
December 18, 2019 18:45
-
-
Save tudorilisoi/cc31a37637e991b69def88a15fab10ec to your computer and use it in GitHub Desktop.
React context with hooks
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 const AppContextProvider = ({ initialData, children }) => { | |
const mergedInitialData = { ...defaults, ...initialData } | |
const [data, setData] = useState(mergedInitialData) | |
useEffect(() => { | |
//I/O | |
console.log(`ctx Update:`, data) | |
}, [data]) | |
const value = { | |
data, | |
setData: (values => setData({ ...data, ...values })), | |
} | |
return ( | |
<AppContext.Provider value={value}> | |
{children} | |
</AppContext.Provider> | |
) | |
} | |
//wrap the app with the context provider | |
<AppContextProvider initialData={data}> | |
<ThemeProvider theme={theme}> | |
<BrowserRouter> | |
<App /> | |
</BrowserRouter> | |
</ThemeProvider> | |
</AppContextProvider> | |
//use the context | |
const LoginPage = (props) => { | |
const ctx = useContext(AppContext) | |
const logout = !ctx.data.user ? null : ( | |
<Button href={`/api/auth/logout`} >Logout {ctx.data.user.username}</Button> | |
) | |
return ({logout}) | |
} | |
//IFTTT |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment