useAuth.jsx 1.4 KB

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