Home > database >  React - Session is lost when page is refreshed
React - Session is lost when page is refreshed

Time:01-23

I am using Firebase, and after login to watch if user is logged in using the following block;

    useEffect(() => {
  const checkAuthToken = () => {
      const token = sessionStorage.getItem('auth-token');
      if (token) {
        setIsAuthenticated(true);
      } else {
        setIsAuthenticated(false);
      }
  }

  window.addEventListener('storage', checkAuthToken);

  return () => {
      window.removeEventListener('storage', checkAuthToken);
  }
}, [])

It works without issue until I refresh the page even sessionStorage data is still on the browser memory.

CodePudding user response:

The idiomatic way to respond to sign in with Firebase is to listen for auth state changes, rather than reading something from local storage yourself.

I recommend sticking to that approach, which is shown in the first snippet in the documentation on getting the current user.

  • Related