Skip to content

Commit

Permalink
feat : 로그인 페이지 리팩토링 (#267)
Browse files Browse the repository at this point in the history
* fix : 중복 선언 제거

* env

* feat : login.ts 실패 처리 삭제

* refactor : 로그인 페이지 로직 분리 / 커스텀 훅 생성

* feat : 로그아웃 함수 작성

* fix : 경로 수정
  • Loading branch information
cmlim0070 authored Dec 6, 2024
1 parent f290768 commit 951a748
Show file tree
Hide file tree
Showing 6 changed files with 89 additions and 122 deletions.
52 changes: 26 additions & 26 deletions .pnp.cjs

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

51 changes: 51 additions & 0 deletions src/hooks/useLogin.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,51 @@
import { useNavigate } from 'react-router-dom';
import { useUserStore } from '@/stores/useUserStore';
import { useToastStore } from '@/hooks/useToastStore';
import { useMutation } from '@tanstack/react-query';
import { login } from '@/service/auth/login';
import { getUserInfo } from '@/service/user/getUserInfo';
import { LoginProps, LoginResponseType } from '@/types/login';
import { tokenStorage } from '@/service/auth/tokenStorage';

export const useLogin = () => {
const navigate = useNavigate();
const { setUser } = useUserStore();
const { addToast } = useToastStore();

const handleGetUserInfo = async (email: string) => {
const userInfoResponse = await getUserInfo();
if (!userInfoResponse) {
addToast('유저 정보를 불러오지 못했습니다.', 'warning');
return false;
}
const userInfoWithEmail = {
nickname: userInfoResponse.nickname || '알 수 없음',
profileImageUrl: userInfoResponse.profileImageUrl || 'testimg.jpg',
email: email
};
setUser(userInfoWithEmail);
return true;
};

const mutation = useMutation({
mutationFn: ({ email, password }: LoginProps) =>
login({ email, password }),
onSuccess: (response: LoginResponseType, { email }) => {
if (response.isSuccess) {
addToast('로그인 되었습니다.', 'success');
tokenStorage.setAccessToken(response.result.accessToken);

Check failure on line 36 in src/hooks/useLogin.ts

View workflow job for this annotation

GitHub Actions / deploy

'response.result' is possibly 'null'.
handleGetUserInfo(email);
navigate('/');
} else {
addToast(response.data.message, 'success');

Check failure on line 40 in src/hooks/useLogin.ts

View workflow job for this annotation

GitHub Actions / deploy

Property 'data' does not exist on type 'LoginResponseType'.
}
},
onError: (error) => {
addToast(error.message, 'warning');
console.error(error);
throw error;
}
});

return mutation;
};
75 changes: 3 additions & 72 deletions src/pages/User/Login/LoginPage.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -2,72 +2,15 @@ import React from 'react';
import { useNavigate } from 'react-router-dom';
import { EmailInput } from '@/components/Common/Input/EmailInput';
import { PasswordInput } from '@/components/Common/Input/PasswordInput';
import { useUserStore } from '@/stores/useUserStore';
import { login } from '@/service/auth/login';
import { getUserInfo } from '@/service/user/getUserInfo';
import { Container } from '@/components/Common/Container/Container';
import { useToastStore } from '@/hooks/useToastStore';
import { LoginResponseType } from '@/types/login';
import { useLogin } from './../../../hooks/useLogin';

export const LoginPage = () => {
const navigate = useNavigate();
const { setUser } = useUserStore();
const { addToast } = useToastStore();
const { mutate } = useLogin();

/**
* 로그인 이후 유저 정보 조회
* @param email
* @returns
*/
const handleGetUserInfo = async (email: string) => {
const userInfoResponse = await getUserInfo();
if (!userInfoResponse) {
addToast('유저 정보를 불러오기를 실패했습니다.', 'warning');
return false;
}
const userInfoWithEmail = {
nickname: userInfoResponse.nickname || '알 수 없음',
profileImageUrl: userInfoResponse.profileImageUrl || 'testimg.jpg',
email: email
};
setUser(userInfoWithEmail);
return true;
};

/**
* 로그인 결과 처리
* @param loginResponse
* @param email
* @returns
*/
const handleLoginResponse = async (
loginResponse: LoginResponseType,
email: string
) => {
switch (loginResponse.code) {
case 'COMMON200': {
addToast('로그인에 성공했습니다.', 'success');
return await handleGetUserInfo(email);
}
case 'USER4000': {
addToast('유저를 찾을 수 없습니다.', 'warning');
return false;
}
case 'USER4001': {
addToast('비밀번호가 일치하지 않습니다.', 'warning');
return false;
}
default:
addToast('로그인 처리에 실패했습니다.', 'warning');
return false;
}
};

/**
* 로그인 폼 제출
* @param e
* @returns
*/
const handleSubmit = async (e: React.FormEvent<HTMLFormElement>) => {
e.preventDefault();
const $loginForm = e.target as HTMLFormElement;
Expand All @@ -82,19 +25,7 @@ export const LoginPage = () => {
return;
}

try {
const loginResponse = await login({ email, password });
const isLoginSuccess = await handleLoginResponse(
loginResponse,
email
);
if (isLoginSuccess) {
navigate('/');
}
} catch (error) {
console.error('에러: ', error);
addToast('서버 오류입니다. 다시 시도해주세요', 'error');
}
mutate({ email, password });
};

const handleNavigateRegister = () => {
Expand Down
3 changes: 2 additions & 1 deletion src/service/api.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@ import { refreshAccessToken } from '@/service/auth/refreshAccessToken';
import { formatApiError } from '@/util/formatApiError';

const baseUrl = import.meta.env.VITE_API_URL as string;
import { logout } from './auth/logout';

export const defaultApi = (option?: AxiosRequestConfig): AxiosInstance => {
const instance = axios.create({
Expand Down Expand Up @@ -41,7 +42,7 @@ export const defaultApi = (option?: AxiosRequestConfig): AxiosInstance => {
`Bearer ${newAccessToken}`;
return instance(originalRequest);
} catch (error) {
tokenStorage.clearTokens();
logout();
window.location.href = '/login';
return Promise.reject(error);
}
Expand Down
Loading

0 comments on commit 951a748

Please sign in to comment.