skip to Main Content

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


  1. const routeLayout: React.FC = ():React.ReactElement => {
        useMemo(async () => {
        const isAuth = await apiCall();
        useContext({ isAuth });
    }, [something])
    
        return (
          <></>
        );
      };
    

    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.

    Login or Signup to reply.
  2. export const useAuthenticated = () => {
      // create state
      const [auth, setAuth] = useState();
      useEffect(() => {
        const isAuth = async () => {
          // assign state
          setAuth(true);
        };
        isAuth();
      }, [setAuth]);
    
      // return state
      return auth;
    };
    
    const routeLayout: React.FC = (): React.ReactElement => {
      // get auth value
      const auth = useAuthentication();
      // pass auth value to the context
      useContext(auth);
    
      return <></>;
    };
    
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search