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

Protected route doesn't work properly after refresh, useEffect problem

I’m trying to protect routes by roles of user, almost everything works fine, but every time I refresh current page, protected route always gives me no access, and by link to I can acces.
I know that It’s something wrong with useEffect I don’t know how can I make It works.

App.js

function App() {
  const [auth, setAuth] = useState();
  const [status, setStatus] = useState();

  useEffect(async () => {
    await Axios.get("http://localhost:5000/api/user").then((res) => {
      setAuth(res.data);
      
    });
  }, [status]);

  return (
    <BrowserRouter>
      <Route element={<ProtectedRoleRoute role={auth?.user?.isAdmin} />}>
        <Route path="admin" element={<Admin />} />
      </Route>
      <Route path="login" element={<Login />} />
      <Route path="noauth" element={<NoAuth />} />
    </BrowserRouter>
  );

ProtectedRoleRoute

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

    function ProtectedRoleRoute(props) {
  return props?.role ? <Outlet /> : <Navigate to="/noauth" replace />;
}

export default ProtectedRoleRoute;

>Solution :

Everytime you refresh the page your state does not persist. An option is to set the auth keyword in the localStorage.

in your useEffect

useEffect(async () => {
    await Axios.get("http://localhost:5000/api/user").then((res) => {
      setAuth(res.data);
      localstorage.setItem(auth, res.data.?user?.isAdmin);
      
    });
  }, [status]);

in your route use

<Route element={<ProtectedRoleRoute role={localStorage.getItem('auth')} />}>

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