I am following this to create protected routes.
Protected Route Component
import React from 'react';
export const ProtectedRoute = ({ isAuthenticated, path, children, navigate, location }) => {
const hasPreviousState = location.key !== 'default';
if (isAuthenticated) {
if (hasPreviousState) {
console.log('previous state');
navigate(-1);
} else {
console.log('no previous state')
navigate('/');
}
}
return children;
}
However, this doesn't seem to work now that I tried it out. The following states I'm trying to achieve are the following:
- If user is authenticated and there was a previous path, go back (navigate(-1)). A scenario this would occur would be if the user was already on the site and they try to log in whilst already logged in.
- If the user is authenticated and there was no previous path, go to home page (navigate('/')). A scenario this would occur if the user opens a new tab or window and enters the following url:
https://website.com/login
The line const hasPreviousState = location.key !== 'default;
never returns true. Not sure why..
What am I missing?
Note
I am using react-router-dom
v6.