Created
September 28, 2021 19:54
-
-
Save deadkff01/ef415c42082df675900dab7fcf312b2a to your computer and use it in GitHub Desktop.
withGlobal HOC
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
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