Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

LocalStorage keeps getting cleared on refreshing React page

I am working on a React app. I store access token in localstorage to authenticate user. But whenever I refresh page, the access token seems to be null. So I keep logging out. I cannot find out what wrong. Please help me with this. Thank you very much.

Here is my login code:

    const navigate = useNavigate();
    const location = useLocation();
    const dispatch = useDispatch();

    // const from = location.state?.from?.pathname || "/admin/documents";

    const [email, setEmail] = useState("");
    const [password, setPassword] = useState("");
    const [message, setMessage] = useState("Đã xảy ra lỗi!");
    const [emailMessage, setEmailMessage] = useState("");
    const [passwordMessage, setPasswordMessage] = useState("");
    const [status, setStatus] = useState(0);
    const [isLoading, setIsLoading] = useState(false);

    const errRef = useRef();

    useEffect(() => {
        localStorage.removeItem("accessToken");
        localStorage.removeItem("refreshToken");
    }, []);

    useEffect(() => {
        setMessage("");
        setEmailMessage("");
        setPasswordMessage("");
    }, [email, password]);

    const validateEmail = () => {
        if (email === "" || email.trim() === "") {
            setEmailMessage("Email không được để trống");
        } else if (!emailRegrex.test(email)) {
            setEmailMessage("Email không hợp lệ");
        }
    };

    const validatePassword = () => {
        if (password === "" || password.trim() === "") {
            setPasswordMessage("Mật khẩu không được để trống");
        }
    };

    const handleSubmit = async (e) => {
        e.preventDefault();

        setIsLoading(true);

        validateEmail();
        validatePassword();

        if (!emailMessage && !passwordMessage) {
            try {
                const response = await axios.post(LOGIN_URL, JSON.stringify({ email, password }), {
                    headers: { "Content-Type": "application/json" },
                    withCredentials: true,
                });

                setIsLoading(false);

                if (response.data.status === 401) {
                    setMessage("Email hoặc mật khẩu không đúng!");
                    setStatus(-1);
                    setTimeout(() => {
                        setStatus(0);
                    }, 4000);
                } else if (response.data.status === 403) {
                    setMessage("Tài khoản không có quyền truy cập!");
                    setStatus(-1);
                    setTimeout(() => {
                        setStatus(0);
                    }, 4000);
                } else if (response.data.status === 400) {
                    setMessage("Có lỗi xảy ra!");
                    setStatus(-1);
                    setTimeout(() => {
                        setStatus(0);
                    }, 4000);
                } else {
                    alert("JJJJJJJJ")
                    setMessage("Đăng nhập thành công!");
                    localStorage.setItem("accessToken", response.data.data.accessToken);
                    localStorage.setItem("refreshToken", response.data.data.refreshToken);

                    const config = {
                        headers: {
                            Authorization: "Bearer " + response.data.data.accessToken,
                        },
                    };

                    const res = await getProfile(config);
                    const user = res.data;

                    dispatch(loginAction.setUser(user));

                    setStatus(1);
                    setTimeout(() => {
                        navigate("/manager/home");
                        setStatus(0);
                    }, 2000);
                }
            } catch (error) {
                setStatus(-1);
                setMessage("Đã xảy ra lỗi!");
                setTimeout(() => {
                    setStatus(0);
                }, 4000);
            }
        }
    };

And my code to attach token:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

useEffect(() => {
        const requestInterceptor = privateAxios.interceptors.request.use(
            (config) => {
                const accessToken = localStorage.getItem("accessToken");

                if (!accessToken) navigate("/admin/login");
                else config.headers.Authorization = `Bearer ${accessToken}`;

                return config;
            },
            (error) => Promise.reject(error),
        );

        const responseInterceptor = privateAxios.interceptors.response.use(
            (response) => {
                if (response.data.status === 401) {
                    if (response.data.message === "User unauthorized. Please log in first.") navigate("/admin/login");
                } else if (response.data.status === 403) navigate("/admin/login");

                return response;
            },
            (error) => {
                return Promise.reject(error);
            },
        );

        return () => {
            privateAxios.interceptors.request.eject(requestInterceptor);
            privateAxios.interceptors.response.eject(responseInterceptor);
        };
    }, [navigate]);
    return privateAxios;

>Solution :

useEffect(() => {
        localStorage.removeItem("accessToken");
        localStorage.removeItem("refreshToken");
    }, []);

This code is the culprict, when ever you refresh the page the above code gets executed in the beginning and removes your accessToken and refreshToken.

Remove this code and let me know if it works.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading