useAuth.jsx 1.3 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859
  1. import React from "react";
  2. import {
  3. login as loginAPI,
  4. logout as logoutAPI,
  5. checkAuthentication,
  6. } from "../utils/api";
  7. import useLocalStorage from "../hooks/useLocalStorage";
  8. const useAuth = () => {
  9. const [isAuthenticated, setIsAuthenticated] = useLocalStorage(
  10. "isAuthenticated",
  11. false
  12. );
  13. const [userId, setUserId] = useLocalStorage("userId", null);
  14. const mountedRef = React.useRef(true);
  15. const login = React.useCallback(
  16. async (userHash, token) => {
  17. await loginAPI(userHash, token);
  18. setIsAuthenticated(true);
  19. setUserId(userHash);
  20. },
  21. [setIsAuthenticated, setUserId]
  22. );
  23. const logout = React.useCallback(async () => {
  24. await logoutAPI();
  25. setIsAuthenticated(false);
  26. setUserId(null);
  27. }, [setIsAuthenticated, setUserId]);
  28. React.useEffect(() => {
  29. const checkAuth = async () => {
  30. const authResult = await checkAuthentication();
  31. if (!authResult) {
  32. setIsAuthenticated(false);
  33. }
  34. };
  35. if (isAuthenticated) {
  36. checkAuth();
  37. }
  38. }, [isAuthenticated, setIsAuthenticated]);
  39. React.useEffect(() => {
  40. return () => {
  41. mountedRef.current = false;
  42. };
  43. }, []);
  44. return {
  45. isAuthenticated,
  46. userId,
  47. login,
  48. logout,
  49. };
  50. };
  51. export default useAuth;