Skip to content

Instantly share code, notes, and snippets.

@satansdeer
Created Mar 3, 2021
Embed
What would you like to do?
// -------------------- 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