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 52 53 | 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 16x 16x 16x 16x 1x 1x 1x 1x 1x 1x 1x 11x 11x 11x 11x 11x 8x 8x 8x 8x 8x 8x 11x 11x 11x 11x 11x 11x 11x 11x | 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;
hasRefreshToken: boolean;
}
export const AuthProvider = ({ children, hasRefreshToken }: Props) => {
const [isAuthenticated, setIsAuthenticated] = useState(hasRefreshToken);
// 초기값 설정
// 페이지가 새로고침 될 때 accessToken이 없으면 refresh 시도, state update 실행
useEffect(() => {
const updateAuthenticated = async () => {
const hasAccessToken = !!Cookies.get('accessToken');
if (!hasAccessToken && hasRefreshToken) {
try {
await API.authService.refresh();
setIsAuthenticated(true);
} catch {
setIsAuthenticated(false);
}
} else if (hasAccessToken) {
setIsAuthenticated(true);
}
};
updateAuthenticated();
}, [hasRefreshToken]);
return (
<AuthContext.Provider value={{ isAuthenticated, setIsAuthenticated }}>
{children}
</AuthContext.Provider>
);
};
|