I am creating a web application with ReactJS that uses the React Router DOM
library.
This application will contain an authentication system that will be used on some routes, for example:
<Routes>
<Route path="/" element={<Login />} />
<Route path="/dashboard" element={ <PrivateRoute><Dashboard /></PrivateRoute>} />
<Route path="/profile" element={ <PrivateRoute><Profile /></PrivateRoute>} />
</Routes>
My <PrivateRoute>
component have the following code:
import { useContext } from 'react';
import { useNavigate } from 'react-router-dom';
import { AuthContext } from '../contexts/authContext';
export default function PrivateRoute({ children }) {
const { accessToken, loading, refreshUser, verifyToken } = useContext(AuthContext);
const navigate = useNavigate();
const doRefresh = async () => {
if(await refreshUser()){
return children;
}
navigate('/');
return;
}
if(loading){
return <div></div>;
}
if(!accessToken){
doRefresh();
}
if(accessToken){
const verify = async () => {
if(await verifyToken()){
return children;
}
doRefresh();
}
verify();
}
return children;
}
The logic of this code was supposed to work perfectly.
When my user opens a private route, the component runs and checks if the accessToken
is null
(false
). If so, it executes the doRefresh()
function, which is responsible for generating a new accessToken
.
If the accessToken
returns true
(have a data) I have to check if the token is still valid, if so, open the children
, if not try to generate a new accessToken
.
The problem with this code is that after the user logs in, the <PrivateRoute>
component is rendered every time along with the continuous execution of the verify
function.
Why is this happening, and how to resolve it?