Created
April 1, 2022 09:51
-
-
Save alissaVrk/42482c0a9b66a2eb209ca254589ab566 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 { SimpleReactiveStore } from './simple-reactive-store'; | |
import React, { useContext, Context, useEffect } from 'react'; | |
type ContextProps<T> = { | |
context: Context<T>; | |
path: string; | |
simpleStore: SimpleReactiveStore; | |
}; | |
export function ContextListener<T>({ context, path, simpleStore }: ContextProps<T>) { | |
const value = useContext(context); | |
useEffect(() => { | |
simpleStore.setValue(path, value); | |
}, [value, simpleStore, path]); | |
return null; | |
} | |
export function LinkProvider<T>({ | |
children, | |
path, | |
context, | |
simpleStore, | |
defaultContextValue, | |
}: React.PropsWithChildren<ContextProps<T> & { defaultContextValue: T }>) { | |
const data = simpleStore.useValue(path, defaultContextValue); | |
return <context.Provider value={data}>{children}</context.Provider>; | |
} |
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
const store = createSimpleReactiveStore(); | |
type CompType = (...args: any) => JSX.Element | null; | |
export function initProviders(parentNode: HTMLElement | null) { | |
if (!parentNode) { | |
throw new Error('there is no root for us..'); | |
} | |
const App = () => { | |
return ( | |
<SomeBusinessLogicProvider> | |
<ContextListener | |
context={someContextContext.SomeContext} | |
path="some=path" | |
simpleStore={store} | |
/> | |
</SomeBusinessLogicProvider> | |
); | |
}; | |
ReactDOM.render(<App />, parentNode); | |
} | |
export function wrapComponentWithProviders<T extends CompType>(Comp: T, reduxStore: StoreType) { | |
return (props: React.ComponentProps<T>) => ( | |
<LinkProvider | |
context={someContextContext.SomeContext} | |
defaultContextValue={someContextContext.defaultValue} | |
path="some=path" | |
simpleStore={store} | |
> | |
<Comp {...props} /> | |
</LinkProvider> | |
); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment