Created
February 14, 2020 17:23
-
-
Save tudorilisoi/4cd2061aaed4c9a05f874ffe8bb54db5 to your computer and use it in GitHub Desktop.
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
import React, { useState, useEffect, useContext } from 'react'; | |
const AppContext = React.createContext(null); | |
export default AppContext; | |
export const defaultData = { | |
loadedItems:[] | |
} | |
// Context provider | |
export const AppContextProvider = ({ initialData, children }) => { | |
const mergedInitialData = { ...defaultData, ...initialData } | |
const [data, setData] = useState(mergedInitialData) | |
//logging | |
useEffect(() => { | |
console.log(`ctx Update:`, data) | |
}, [data]) | |
const value = { | |
data, | |
setData: (values => setData({ ...data, ...values })), | |
} | |
return ( | |
<AppContext.Provider value={value}> | |
{children} | |
</AppContext.Provider> | |
) | |
} | |
//wrapping a class with context or other hooks | |
const wrapWithHooks = (C, hooks) => { | |
const name = `withConfirm-${C.displayName || C.name}` | |
function withHooks(props) { | |
const hookValues = {} | |
Object.keys(hooks).forEach(k=>{ | |
hookValues[k] = hooks[k]() | |
}) | |
const finalProps = { ...props, ...hookValues } | |
return ( | |
<C {...finalProps} /> | |
) | |
} | |
withHooks.displayName = name | |
return withHooks | |
} | |
const HookedLoginPage = withHooks(LoginPage, {appContext:()=>useContext(AppContext)}) | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment