import { useAppDispatch, useAppSelector } from "@/store/hooks"; import { useEffect } from "react"; import { setIsAuth, setUserName } from "./reducer"; export const useAuth = () => { const dispatch = useAppDispatch(); const { isAuth, userName } = useAppSelector((store) => store.auth); useEffect(() => { const storedUserName = localStorage.getItem("user_name"); if (storedUserName != null && storedUserName.trim().length > 0) { dispatch(setIsAuth(true)); dispatch(setUserName(storedUserName)); } else { dispatch(setIsAuth(false)); dispatch(setUserName("")); localStorage.removeItem("user_name"); } }, [dispatch]); const login = ({ name }: { name: string }) => { dispatch(setIsAuth(true)); dispatch(setUserName(name)); localStorage.setItem("user_name", name); }; const logout = () => { localStorage.removeItem("user_name"); dispatch(setIsAuth(false)); dispatch(setUserName("")); }; return { login, isAuth, userName, logout }; };