Controlling Page Re rendering While Checking Token Expiration in React Using useEffect

15 views Asked by At

I'm working on a React application where I need to check the expiration of a user token. However, I've encountered an issue where the page re-renders every second due to the token expiration check being placed inside a useEffect. Here are the details:

In my React application, I'm using a token-based authentication system. I want to check the expiration of the user's token and handle it appropriately (e.g., redirect to login page) when it expires. To do this, I've placed the token expiration check inside a useEffect. However, this results in the component re-rendering every second, which is not the desired behavior.

useEffect(() => {
  const checkTokenExpiration = () => {
    console.log('Effect is running');
    const storedToken = localStorage.getItem('token');
    console.log('stored token');
    console.log(storedToken);

    if (storedToken) {
      console.log('Checking token expiration...');
      try {
        const decodedToken = jwtDecode(storedToken);
        const expirationTime = decodedToken.exp * 1000;
        const currentTime = new Date().getTime();

        if (currentTime > expirationTime) {
          console.error('Token expired');
          localStorage.removeItem('token');
          setIsAuthenticated(false);
          setIsTokenExpired(true);
          window.location.href = '/';
          warn('Your Session has expired! Sign in again!');
        } else {
          setIsAuthenticated(true);
          setIsTokenExpired(false);
          setToken(storedToken);
          setUserRole(decodedToken.role);
          setUserName(decodedToken.name);
          setUserTimetable(decodedToken.timetable);
          setUserDesig(decodedToken.designation);
          setUserPhone(decodedToken.mobile);
          setUserEmail(decodedToken.email);

          if (typeof decodedToken.profile === 'undefined' || decodedToken.profile.trim() === '') {
            console.log('Profile pic not found');
            setProfilePicUrl(`${process.env.PUBLIC_URL}/img/Faculty pics/prof.png`);
          } else {
            setProfilePicUrl(decodedToken.profile);
          }
        }
      } catch (error) {
        console.error('Error decoding stored token:', error);
      }
    }
  };
  checkTokenExpiration();
  const intervalId = setInterval(checkTokenExpiration, 1000);
  return () => clearInterval(intervalId);
}, []); 

0

There are 0 answers