Spaces:
Running
Running
File size: 1,020 Bytes
79278ec |
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 |
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 };
};
|