| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051 |
- 'use client';
- import { createContext, useContext, useEffect, useState, useCallback } from 'react';
- import { checkAuthServer } from '@/lib/api/auth';
- // 인증 상태 Context
- const AuthContext = createContext<{
- isLoading: boolean;
- isAuthenticated: boolean;
- setIsAuthenticated: (value: boolean) => void;
- checkAuth: () => Promise<boolean>;
- }>({
- isLoading: true,
- isAuthenticated: false,
- setIsAuthenticated: () => {},
- checkAuth: async () => false
- });
- // Context Provider
- export function AuthProvider({ children }: { children: React.ReactNode }) {
- const [isAuthenticated, setIsAuthenticated] = useState<boolean>(false);
- const [isLoading, setIsLoading] = useState<boolean>(true);
- const checkAuth = useCallback(async (): Promise<boolean> => {
- try {
- const ret = await checkAuthServer();
- setIsAuthenticated(ret);
- setIsLoading(false);
- return ret;
- } catch {
- console.error("인증 확인 중 오류 발생");
- setIsAuthenticated(false);
- return false;
- }
- }, []);
- useEffect(() => {
- checkAuth();
- }, [checkAuth]);
- return (
- <AuthContext.Provider value={{ isLoading, isAuthenticated, setIsAuthenticated, checkAuth }}>
- {children}
- </AuthContext.Provider>
- );
- }
- // Context 사용을 위한 커스텀 훅
- export function useAuthContext() {
- return useContext(AuthContext);
- }
|