Skip to content

Instantly share code, notes, and snippets.

@tudorilisoi
Created February 14, 2020 17:23
Show Gist options
  • Save tudorilisoi/4cd2061aaed4c9a05f874ffe8bb54db5 to your computer and use it in GitHub Desktop.
Save tudorilisoi/4cd2061aaed4c9a05f874ffe8bb54db5 to your computer and use it in GitHub Desktop.
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