I wanted to refresh the token every 1 hour ONLY if there is a user activity.
Otherwise just remove the token.
Currently, my code below does call the refresh api every 1 hour regardless whether there is user activity or not.
User activity is any movement on your keyboard or mouse.
const App = () => {
const refreshTokenInterval = () => {
try {
const isLoggedIn = useAuthStore.getState().isLoggedIn;
if (isLoggedIn) {
AuthenticationService.refresh(null, (response) =>
CookieService.set(activeAccount, response.data)
);
}
} catch (error) {
console.log(error);
} finally {
setTimeout(refreshTokenInterval, 1000 * 60 * 60);
}
};
useEffect(() => {
refreshTokenInterval();
}, []);
return null;
};
export default App;
4
Answers
This will refresh your token once every time user is inactive for 1 hour if my define of your user activity is right
You could try out the below solution
Above code you could add to Parent component. It will track the user activity in case user was not active for more than certain time it will trigger the onIdle function. Where you can add your logic related to refresh token
NPM – https://www.npmjs.com/package/react-idle-timer?activeTab=readme
you can use useEffect in setTimeout function and time set 1 hour
I’ve abstracted the logic into a hook. The basic logic is based on a running interval that calls the
refreshTokenInterval
handler once every hour (or any interval you need), and event listeners that detect if there was any activity at all during the previous interval’s duration. If there was activity the therefreshTokenInterval
completes the token refresh logic, otherwise if there was no activityrefreshTokenInterval
kills the running interval and clears the activity event listeners.Code:
Usage:
In this example I extracted
activeAccount
as an external dependency, so this value may need to be memoized in order to provide it as a stable reference since it is referenced in auseEffect
hook’s dependency array.Demo
Here’s a demo using a 10 second token refresh/activity interval.