Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Fix: #233 새로고침 시 zustand 스토어 초기화되는 문제 수정 #263

Merged
merged 7 commits into from
Nov 5, 2024
4 changes: 2 additions & 2 deletions src/components/common/Header.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -45,9 +45,9 @@ export default function Header() {
<button
type="button"
className="ml-10 h-20 rounded-md bg-white px-4 tracking-tight hover:brightness-90"
onClick={isAuthenticated || userInfoData.userId ? handleLogout : () => navigate('/signin')}
onClick={isAuthenticated ? handleLogout : () => navigate('/signin')}
>
{isAuthenticated || userInfoData.userId ? 'Logout' : 'Login'}
{isAuthenticated ? 'Logout' : 'Login'}
</button>
</nav>
</header>
Expand Down
3 changes: 0 additions & 3 deletions src/components/user/auth-form/ProfileImageContainer.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -61,9 +61,6 @@ export default function ProfileImageContainer({ imageUrl, setImageUrl }: Profile
}

uploadImageMutate({ file });

const localImageUrl = URL.createObjectURL(file);
setImageUrl(localImageUrl);
};

const handleRemoveImg = () => {
Expand Down
7 changes: 2 additions & 5 deletions src/mocks/services/authServiceHandler.ts
Original file line number Diff line number Diff line change
Expand Up @@ -208,10 +208,7 @@ const authServiceHandler = [
}),

// 액세스 토큰 갱신 API
http.post(`${BASE_URL}/user/refresh`, async ({ cookies, request }) => {
const accessToken = request.headers.get('Authorization');
if (!accessToken) return new HttpResponse(null, { status: 401 });

http.post(`${BASE_URL}/user/refresh`, async ({ cookies }) => {
const { refreshToken, refreshTokenExpiresAt } = cookies;
const cookieRefreshToken = Cookies.get('refreshToken');

Expand All @@ -228,7 +225,7 @@ const authServiceHandler = [
return HttpResponse.json({ message: '리프레시 토큰이 만료되었습니다.' }, { status: 401 });
}

const userId = convertTokenToUserId(accessToken);
const userId = convertTokenToUserId(refreshToken);
if (!userId) return new HttpResponse(null, { status: 401 });

const newAccessToken = generateDummyToken(userId);
Expand Down
35 changes: 31 additions & 4 deletions src/routes/AfterLoginRoute.tsx
Original file line number Diff line number Diff line change
@@ -1,11 +1,38 @@
import { useEffect, type PropsWithChildren } from 'react';
import { Navigate, Outlet, useNavigate } from 'react-router-dom';
import useToast from '@hooks/useToast';
import useStore from '@stores/useStore';
import type { PropsWithChildren } from 'react';
import { Navigate, Outlet } from 'react-router-dom';
import { getAccessToken } from '@services/authService';

export default function AfterLoginRoute({ children }: PropsWithChildren) {
const { isAuthenticated, userInfo } = useStore();
const { toastError } = useToast();
const navigate = useNavigate();
const { onLogout, onLogin, clearUserInfo, accessToken, isAuthenticated } = useStore();

if (!isAuthenticated && !userInfo.userId) return <Navigate to="/signin" replace />;
useEffect(() => {
const autoRefreshToken = async () => {
try {
const refreshResponse = await getAccessToken();
const newAccessToken = refreshResponse.headers.authorization;

if (!newAccessToken) throw new Error('토큰 발급에 실패했습니다.');

onLogin(newAccessToken.split(' ')[1]);
} catch (error) {
// 토큰 갱신 실패 시 처리
toastError('로그인 정보가 만료되었습니다. 다시 로그인 해주세요.');
setTimeout(() => {
onLogout();
clearUserInfo();
navigate('/signin', { replace: true });
}, 2000);
}
};

if (isAuthenticated && !accessToken) autoRefreshToken();
}, [accessToken]);
Yoonyesol marked this conversation as resolved.
Show resolved Hide resolved
Yoonyesol marked this conversation as resolved.
Show resolved Hide resolved

if (!isAuthenticated) return <Navigate to="/signin" replace />;

return children || <Outlet />;
}
4 changes: 2 additions & 2 deletions src/routes/BeforeLoginRoute.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -3,9 +3,9 @@ import type { PropsWithChildren } from 'react';
import { Navigate, Outlet } from 'react-router-dom';

export default function BeforeLoginRoute({ children }: PropsWithChildren) {
const { isAuthenticated, userInfo } = useStore();
const { isAuthenticated } = useStore();

if (isAuthenticated || userInfo.userId) return <Navigate to="/" replace />;
if (isAuthenticated) return <Navigate to="/" replace />;

return children || <Outlet />;
}
2 changes: 2 additions & 0 deletions src/stores/useStore.ts
Original file line number Diff line number Diff line change
Expand Up @@ -136,6 +136,8 @@ export const useStore = create<Store>()(
})),
partialize: (state) => ({
userInfo: state.userInfo,
isAuthenticated: state.isAuthenticated,
isVerified: state.isVerified,
}),
},
),
Expand Down