Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to execute useEffect every time outlet changes

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?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

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

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading