Skip to content

Commit

Permalink
feat: refresh 대응 위해 authContext localStorage 에 저장
Browse files Browse the repository at this point in the history
  • Loading branch information
PMtHk committed Nov 19, 2024
1 parent a1d51dc commit 45db539
Showing 1 changed file with 36 additions and 5 deletions.
41 changes: 36 additions & 5 deletions apps/client/src/contexts/authContext.tsx
Original file line number Diff line number Diff line change
@@ -1,4 +1,12 @@
import { createContext, ReactNode, useCallback, useContext, useMemo, useState } from 'react';
import {
createContext,
ReactNode,
useCallback,
useContext,
useMemo,
useState,
useEffect,
} from 'react';

export interface AuthContext {
isAuthenticated: boolean;
Expand All @@ -8,6 +16,8 @@ export interface AuthContext {
accessToken: string;
}

export const AUTH_STORAGE_KEY = 'auth_context';

export const initialAuthContext: AuthContext = {
isAuthenticated: false,
login: async () => {},
Expand All @@ -16,12 +26,34 @@ export const initialAuthContext: AuthContext = {
accessToken: '',
};

const loadInitialState = () => {
const savedState = localStorage.getItem(AUTH_STORAGE_KEY);
if (savedState) {
const { isAuthenticated, username, accessToken } = JSON.parse(savedState);
return { isAuthenticated, username, accessToken };
}

return {
isAuthenticated: false,
username: '',
accessToken: '',
};
};

const AuthContext = createContext<AuthContext>(initialAuthContext);

export function AuthProvider({ children }: { children: ReactNode }) {
const [isAuthenticated, setIsAuthenticated] = useState<boolean>(false);
const [username, setUsername] = useState<string>('');
const [accessToken, setAccessToken] = useState<string>('');
const initialState = loadInitialState();
const [isAuthenticated, setIsAuthenticated] = useState<boolean>(initialState.isAuthenticated);
const [username, setUsername] = useState<string>(initialState.username);
const [accessToken, setAccessToken] = useState<string>(initialState.accessToken);

useEffect(() => {
localStorage.setItem(
AUTH_STORAGE_KEY,
JSON.stringify({ isAuthenticated, username, accessToken })
);
}, [isAuthenticated, username, accessToken]);

const login = useCallback(async (username: string, accessToken: string) => {
setIsAuthenticated(true);
Expand Down Expand Up @@ -54,6 +86,5 @@ export const useAuth = () => {
if (!context) {
throw new Error('useAuth must be used within an AuthProvider');
}

return context;
};

0 comments on commit 45db539

Please sign in to comment.