Home > database >  How to execute useEffect every time outlet changes
How to execute useEffect every time outlet changes

Time:03-17

Here's my code in react:

function ProtectedRoutes(props) {

    useEffect(() => {

        setTimeout(props.verify_access, 100)

    }, [])

    const { isAuth } = props
    
    if(isAuth){

        return <Outlet />
    }else{

        return <Navigate to={"/login"}/>
    }

}


const mapStateToProps  = state => {

    return {
        isAuth: state.auth.isAuthenticated
    }
}

export default connect(mapStateToProps, { verify_access })(ProtectedRoutes)

So what's going on here is that I'm trying to make a protected routes for authenticated users only. I'm authenticating users with JWT stored in localStorage and I need the redux action props.verify_access to check for the JWT every time user goes to a different page. As you can probably see by now, that's not gonna happen because apparently the the useEffect hook will only run when the parent route is first initialized, if I go to any route inside the parent route the useEffect will not do anything. I tried to put in Outlet in the useEffect array but it doesn't work

How do I execute useEffect every time the user loads a new Protected Routes?

CodePudding user response:

Use the useLocation hook to access the location object and use the pathname as a dependency for the useEffect hook.

Example:

import { Navigate, Outlet, useLocation } from 'react-router-dom';

function ProtectedRoutes({ isAuth, verify_access }) {
  const location = useLocation();

  useEffect(() => {
    setTimeout(verify_access, 100);
  }, [location.pathname, verify_access]);

  return isAuth ? <Outlet /> : <Navigate to="/login" replace />;
}

Edit how-to-execute-useeffect-every-time-outlet-changes

  • Related