today I'm having an issue where react loads the route before my API verifies that the user's JWT token is valid. When using EJS I could pass in a middleware to the route and the middleware would not contain the next() parameter. As a result the server wouldn't render the EJS which is exactly what I want to achieve with react. Also is it possible to make useNavigate not reload when navigating the that specific route?
My routes in App.js currently look like this:
<Route element={<ProtectedRoute access={access}></ProtectedRoute>}>
<Route
path="/login"
exact
element={<Login login={login} access={access}></Login>}
></Route>
<Route
path="/signup"
exact
element={<Signup signup={signup} access={access}></Signup>}
></Route>
<Route
path="/forgot-password"
exact
element={<ForgotPassword access={access}></ForgotPassword>}
></Route>
<Route
path="/reset-password"
exact
element={<ResetPassword access={access}></ResetPassword>}
></Route>
</Route>;
The access function looks like this:
const access = async (token) => {
return await axios.post(
"http://localhost:5000/access",
{},
{ headers: { Authorization: `Bearer ${token}` } }
);
};
The protected route component looks like this:
import { useState, useContext } from "react";
import { useLocation, useNavigate, Outlet } from "react-router-dom";
import AuthContext from "../Context/AuthProvider";
const ProtectedRoute = ({ access }) => {
const [authorized, setAuthorized] = useState(false);
const { auth } = useContext(AuthContext);
const navigate = useNavigate();
const authorize = async () => {
try {
await access(auth.accessToken);
setAuthorized(true);
} catch (err) {
setAuthorized(false);
}
};
authorize();
if (authorized) {
navigate('/');
} else {
return <Outlet></Outlet>;
}
};
export default ProtectedRoute;
When I use this code my login component renders a bit before the code navigates back to the home page, how do I make the login component not render at all and just make it stay on the home page?