Created
March 3, 2021 10:26
-
-
Save satansdeer/0fe7e444b659b580cdb6bc768c1d3de3 to your computer and use it in GitHub Desktop.
This file contains hidden or 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
// -------------------- 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