I am building a react app to learn react. I have implemented context to store information about the user when they login and also am making a copy in the localstorage. I verify that users are logged in like this in the App component
function App() {
const [user, setUser] = useContext(UserContext);
return (
<div className="App">
<Router>
<NavBar />
<Switch>
<Route path="/login" exact>
{!user.loggedIn ? <LoginForm /> : <Redirect to="/profile" />}
</Route>
</Switch>
</Router>
</div>
);
And this works fairly well. But if the token has expired; I want the user to be forced into the login page. Which means I need to check the expiration time on every route request as users can be in there profile and if they click on another link they will be redirected to login component. How should I approach this? I have tried to to use useEffect in app component that sets the state loggedIn to true true when it meets the condition and made a comparison like
useEffect(function () {
const ct = parseInt(Date.now().toString(), 10);
const iat = parseInt(localStorage.getItem('iat'), 10);
if (ct - iat < 60000) {
setUser({ loggedIn: true });
} else {
setUser({ loggedIn: false });
}
});
From my understanding this should happen everytime App component is rendered hence I provide no input to useEffect but this obviously throws a maximum update depth reached
error.
How should I implement this behaviour?