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

38 Views Asked by At

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

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

export default ProtectedRoleRoute;
1

There are 1 best solutions below

0
Harsh Gupta On BEST ANSWER

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')} />}>