Skip to content

Instantly share code, notes, and snippets.

@deadkff01
Created September 28, 2021 19:54
Show Gist options
  • Save deadkff01/ef415c42082df675900dab7fcf312b2a to your computer and use it in GitHub Desktop.
Save deadkff01/ef415c42082df675900dab7fcf312b2a to your computer and use it in GitHub Desktop.
withGlobal HOC
import { FC, useCallback } from "react";
import { useGlobal, ACTIONS, GlobalContextProps } from "../contexts/global";
export interface IGlobal extends GlobalContextProps {
requestHandler: (requestFunction: () => {}) => Promise<any>;
}
interface IWrappedComponent {
global: IGlobal;
}
export const withGlobal = (WrappedComponent: FC<IWrappedComponent>) => {
const HOC = () => {
const { state, dispatch } = useGlobal();
const requestHandler = useCallback(
async (requestFunction) => {
try {
dispatch({ type: ACTIONS.IS_LOADING, payload: true });
return await requestFunction();
} catch (error) {
dispatch({
type: ACTIONS.SHOW_ERROR,
payload: error?.response?.data || true
});
} finally {
dispatch({ type: ACTIONS.IS_LOADING, payload: false });
}
},
[dispatch]
);
const props: IGlobal = {
state,
dispatch,
requestHandler
};
return <WrappedComponent global={props} />;
};
return HOC;
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment