Skip to content

Instantly share code, notes, and snippets.

@satansdeer
Created March 3, 2021 10:26
Show Gist options
  • Save satansdeer/0fe7e444b659b580cdb6bc768c1d3de3 to your computer and use it in GitHub Desktop.
Save satansdeer/0fe7e444b659b580cdb6bc768c1d3de3 to your computer and use it in GitHub Desktop.
// -------------------- HOC definition ----
type InjectedProps = {
initialState: AppState
}
export function withData<TProps>(
WrappedComponent: React.JSXElementConstructor<TProps & InjectedProps>
) {
const WrapperComponent: React.FC<Omit<TProps, keyof InjectedProps>> = ({ children, ...props }) => {
const [initialState, setInitialState] = useState<AppState>({
lists: [],
draggedItem: undefined,
})
return (
<WrappedComponent {...props as TProps} initialState={initialState}>
{children}
</WrappedComponent>
)
}
return WrapperComponent
}
// ----------------------------- HOC Usage ------
type AppStateProviderProps = {
children?: React.ReactNode
}
export const AppStateProvider = withData<AppStateProviderProps>(({ children, initialState }) => {
const [state, dispatch] = useReducer(appStateReducer, initialState)
return (
<AppStateContext.Provider
value={{ state, dispatch }}
>
{children}
</AppStateContext.Provider>
)
})
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment