I'm trying to do the same thing as this answer, then created a component named ProtectedRoute.
Placed ProtectedRoute in App.tsx. This is supposed to render multiple ProtectedRoute components maping over ProtectedRoutes.
When the ProtectedRoute component gets rendered it sends an HTTP request to verify the token.
useLayoutEffect(() => {
axios
.get('http://localhost:5000/authorization', {
withCredentials: true,
})
.then((response) => {
setHasValidToken(true);
console.log('valid token!');
})
.catch((error) => {
if (error.response.data.message) {
console.error(error.response.data.message);
} else {
console.error(`Error: ${error}`);
}
setHasValidToken(false);
navigate('/login');
});
}, [navigate]);
Based on the result, it sets the state hasValidToken. Then return the following.
return (
<>
{hasValidToken ? (
<Route path={path} element={element} />
) : (
<Navigate to="/login" />
)}
</>
);
However, this ternary operator seems not working correctly. What's more, it never console log the messages in the component. (I placed some console.log in the component)
I also tried to comment out everything inside return in the component, but still all protected route's path got rendered.
It's weird that all routes still can be rendered even though ProtectedRoute returns nothing.
I hope this makes sense and get help to figure out what's going on and what I might miss.