'Why is my local storage item removed after a short period automatically?

I have a custom popup modal for user authentication in react.js and it redirects to the main page after successful authentication.

Meanwhile, it should save a local storage item named accessToken in JWT.

But what I've noticed is that the accessToken is saved in local storage sometimes, but sometimes the accessToken is removed automatically even it is saved beforehand.

enter image description here

In other words, it doesn't work every time, just works sometimes.

Here's my login popup.

import React, {
    useEffect,
    useRef,
    useState
} from 'react';
import { number } from "yup";

const createPopup = ({
    url,
    title,
    height,
    width,
}) => {
    const left = window.screenX + (window.outerWidth - width) / 2;
    const top = window.screenY + (window.outerHeight - height) / 2.5;

    return window.open(
        url,
        title,
        `width=${width}, height=${height}, left=${left}, top=${top}`,
    );
};

const LoginPopup = ({
    title = '',
    width = 500,
    height = 500,
    url,
    children,
    onCode,
    onClose,
}) => {
    const [externalWindow, setExternalWindow] = useState(Window | null);
    const intervalRef = useRef(number);

    const clearTimer = () => {
        window.clearInterval(intervalRef.current);
    };

    const onContainerClick = () => {
        setExternalWindow(createPopup({
            url, title, width, height,
        }));
    };

    useEffect(() => {
        if (externalWindow) {
            intervalRef.current = window.setInterval(() => {
                try {
                    const currentUrl = externalWindow.location.href;
                    const params = new URL(currentUrl).searchParams;
                    const code = params.get('code');

                    if (!code) {
                        return;
                    }

                    onCode(code, params);
                    clearTimer();
                    externalWindow.close();
                } catch (error) {
                    // eslint-ignore-line
                } finally {
                    if (!externalWindow || externalWindow.closed) {
                            onClose();
                            clearTimer();
                    }
                }
            }, 200);
        }

        return () => {
            if (externalWindow) externalWindow.close();
            if (onClose) onClose();
        };
    }, [externalWindow]);

    return (
        // eslint-disable-next-line
        <div onClick={() => onContainerClick()}>
            {children}
        </div>
    );
};

export default LoginPopup;

onCode is from Context

const setSession = (key, value) => {
  if (key && value) {
    localStorage.setItem(key, value);
  } else {
    localStorage.removeItem(key);
  }
};

...
export const AuthProvider = ({ children }) => {
  const login = async (accessToken, params) => {
    setSession('accessToken', accessToken);

    try {
      const response = await axios.get(`${domain}/api/v1/account`);
      const user = response?.data;

      dispatch({
        type: 'LOGIN',
        payload: {
          user
        }
      });
    } catch (err) {
      console.error(err);
    }
  };

  useEffect(() => {
    const initialise = async () => {
    ...
    };
    initialise();
  }, []);

  return (
    <AuthContext.Provider
      value={{
        ...state,
        ...
        login,
        logout
      }}
    >
      {children}
    </AuthContext.Provider>
  );
};

export const AuthContext;

Not sure why it is removed immediately after the popup is closed even it is saved in the local storage but a very short period.

I am pretty sure the back-end has the correct redirection url so it should work correctly.



Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source