All files / src/providers/provider-auth index.tsx

94.11% Statements 48/51
57.14% Branches 4/7
100% Functions 3/3
94.11% Lines 48/51

Press n or j to go to the next uncovered block, b, p or k for the previous block.

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 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 521x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 14x 14x 14x 14x 1x 1x 1x 1x 1x 1x 6x 6x 6x 6x 6x 6x 6x 6x 6x 6x   6x 6x 6x 6x     6x 6x 6x 6x 6x 6x 6x 6x 6x 6x  
import React, { createContext, SetStateAction, useContext, useEffect, useState } from 'react';
 
import Cookies from 'js-cookie';
 
import { API } from '@/api';
 
interface AuthContextType {
  isAuthenticated: boolean;
  setIsAuthenticated: React.Dispatch<SetStateAction<boolean>>;
}
 
const AuthContext = createContext<AuthContextType | null>(null);
 
export const useAuth = () => {
  const context = useContext(AuthContext);
  if (!context) throw new Error('useAuth must be used in AuthProvider');
  return context;
};
 
interface Props {
  children: React.ReactNode;
}
 
export const AuthProvider = ({ children }: Props) => {
  const [isAuthenticated, setIsAuthenticated] = useState(false);
 
  // 초기값 설정
  // 페이지가 새로고침 될 때 accessToken이 없으면 refresh 시도, state update 실행
  useEffect(() => {
    const updateAuthenticated = async () => {
      const accessToken = Cookies.get('accessToken');
      if (!accessToken) {
        try {
          await API.authService.refresh();
          setIsAuthenticated(true);
        } catch {
          setIsAuthenticated(false);
        }
      } else {
        setIsAuthenticated(true);
      }
    };
    updateAuthenticated();
  }, []);
 
  return (
    <AuthContext.Provider value={{ isAuthenticated, setIsAuthenticated }}>
      {children}
    </AuthContext.Provider>
  );
};