authProvider.tsx 1.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051
  1. 'use client';
  2. import { createContext, useContext, useEffect, useState, useCallback } from 'react';
  3. import { checkAuthServer } from '@/lib/api/auth';
  4. // 인증 상태 Context
  5. const AuthContext = createContext<{
  6. isLoading: boolean;
  7. isAuthenticated: boolean;
  8. setIsAuthenticated: (value: boolean) => void;
  9. checkAuth: () => Promise<boolean>;
  10. }>({
  11. isLoading: true,
  12. isAuthenticated: false,
  13. setIsAuthenticated: () => {},
  14. checkAuth: async () => false
  15. });
  16. // Context Provider
  17. export function AuthProvider({ children }: { children: React.ReactNode }) {
  18. const [isAuthenticated, setIsAuthenticated] = useState<boolean>(false);
  19. const [isLoading, setIsLoading] = useState<boolean>(true);
  20. const checkAuth = useCallback(async (): Promise<boolean> => {
  21. try {
  22. const ret = await checkAuthServer();
  23. setIsAuthenticated(ret);
  24. setIsLoading(false);
  25. return ret;
  26. } catch {
  27. console.error("인증 확인 중 오류 발생");
  28. setIsAuthenticated(false);
  29. return false;
  30. }
  31. }, []);
  32. useEffect(() => {
  33. checkAuth();
  34. }, [checkAuth]);
  35. return (
  36. <AuthContext.Provider value={{ isLoading, isAuthenticated, setIsAuthenticated, checkAuth }}>
  37. {children}
  38. </AuthContext.Provider>
  39. );
  40. }
  41. // Context 사용을 위한 커스텀 훅
  42. export function useAuthContext() {
  43. return useContext(AuthContext);
  44. }