Home > Net >  I get logged out when I refresh the page
I get logged out when I refresh the page

Time:07-10

I am getting logged out when I'm refreshing the page in my React JS web app. I used localStorage and it worked well, not that I switched to cookies, I get logged out whenever I refresh. The cookies is still stored in the browser though. As you can see in the code below, I try to check if there is a token so I can be logged in but I don't know why that doesn't work with cookies. It used to work with local Storage though.

Cookies stored in browser

my auth-hook.js

import { useState, useCallback, useEffect, useLayoutEffect } from 'react';
import Cookies from 'js-cookie';

let logoutTimer;

export const useAuth = () => {
  const [token, setToken] = useState(false);
  const [tokenExpirationDate, setTokenExpirationDate] = useState();
  const [userId, setUserId] = useState(false);
  const [isAdmin, setIsAdmin] = useState(false);

  const login = useCallback((userRole, uid, token, expirationDate) => {
    setToken(token);
    setUserId(uid);
    if (userRole === 'admin') {
      setIsAdmin(true);
    } else if (userRole !== 'admin') {
      setIsAdmin(false);
    }
    const tokenExpirationDate =
      expirationDate || new Date(new Date().getTime()   1000 * 60 * 60);
    setTokenExpirationDate(tokenExpirationDate);
    Cookies.set(
      "userData",
      JSON.stringify({
        userRole: userRole,
        userId: uid,
        token: token,
        expiration: tokenExpirationDate.toISOString(),
      })
    );
  }, []);

  const logout = useCallback(() => {
    setIsAdmin(false);
    setToken(null);
    setTokenExpirationDate(null);
    setUserId(null);
    Cookies.remove('userData');
  }, []);

  useEffect(() => {
    if (token && tokenExpirationDate) {
      const remainingTime =
        tokenExpirationDate.getTime() - new Date().getTime();
      logoutTimer = setTimeout(logout, remainingTime);
    } else {
      clearTimeout(logoutTimer);
    }
  }, [token, logout, tokenExpirationDate]);

  useLayoutEffect(() => {
    const storedData = Cookies.get("userData");
    if (
      storedData &&
      storedData.token &&
      new Date(storedData.expiration) > new Date()
    ) {
      login(
        storedData.userRole,
        storedData.userId,
        storedData.token,
        new Date(storedData.expiration)
      );
    }
  }, [login]);
  return {
  token,
  userId,
  isAdmin,
  login,
  logout,
  }
}

CodePudding user response:

You need to parse the json before accessing it.

const storedData = JSON.parse(Cookies.get("userData"));
//....
  • Related