Press n or j to go to the next uncovered block, b, p or k for the previous block.
| 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 | import { useAppSelector } from "@redux/hooks";
import { selectAuth } from "@redux/slices/auth/auth";
import Cookies from "js-cookie";
import { useEffect, useLayoutEffect, useRef, useState } from "react";
export const useCookieListener = () => {
const [cookie, setCookie] = useState<string | undefined>(Cookies.get("user"));
const isAuthenticated = useAppSelector(selectAuth);
const prevCookieRefType = useRef<string>(typeof cookie);
const isLoggedOut = useRef<boolean>(false);
useEffect(() => {
const controller = new AbortController();
document.addEventListener(
"mouseenter",
(e) => {
const newCookie = Cookies.get("user");
// Base condition => user can be either logged in or logged out
const baseCondition =
prevCookieRefType.current === "undefined" ||
prevCookieRefType.current === "string";
// 1. case => user was logged out and logged in (undefined, string)
// 2. case => user was already logged in and refreshed the page (string, string)
const didLoggedUserLogOut =
baseCondition && typeof newCookie === "undefined";
if (didLoggedUserLogOut) {
isLoggedOut.current = didLoggedUserLogOut;
setCookie(newCookie);
}
},
{ passive: true },
);
return controller.abort();
}, []);
useLayoutEffect(() => {
if (isLoggedOut.current && isAuthenticated) window.location.reload();
}, []);
};
|