I am working on code where someone has created custom hooks for context and authentication. I am trying to add a route layout provider and run those hooks inside that component so it only affects particular routes.
RouteLayout Component
const routeLayout: React.FC = ():React.ReactElement => {
useAuthentication();
//I only want to run the context hook if useAuthentication returns true.
useContext();
return (
<></>
);
};
export routeLayout
Code for useAuthentication
export const useAuthenticated = async() : Promise<void> => {
useEffect(() => {
const isAuth = async () => {
//Call API and check if the token is valid
};
isAuth();
},[something]);
};
How do I return something from useEffect – useAuthentication so I can only run the context code if it is valid token. Please also tell if there is better way to do this
2
Answers
You can use async here and rap your function in a memo and then await the response in order to know what the hook should do. A prop key within the context to let it know if it should run based on if isAuth is true or not would resolve this.