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 54 55 56 57 58 59 60 61 62 63 64 65 | 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x | 'use client';
import { useSearchParams } from 'next/navigation';
import { useCallback, useState } from 'react';
import axios, { AxiosError } from 'axios';
import { API } from '@/api';
import { normalizePath } from '@/lib/auth/utils';
import { useAuth } from '@/providers';
import { LoginRequest } from '@/types/service/auth';
import { CommonErrorResponse } from '@/types/service/common';
const getLoginErrorMessage = (problem: CommonErrorResponse) => {
if (
problem.errorCode === 'USER_NOT_FOUND' ||
problem.errorCode === 'INVALID_PASSWORD_VALUE' ||
problem.errorCode === 'INVALID_INPUT_VALUE'
) {
return '이메일 또는 비밀번호가 일치하지 않습니다.';
}
return '로그인에 실패했습니다.';
};
export const useLogin = () => {
const searchParams = useSearchParams();
const [loginError, setLoginError] = useState<string | null>(null);
const clearLoginError = useCallback(() => setLoginError(null), []);
const { setIsAuthenticated } = useAuth();
const handleLogin = async (payload: LoginRequest, formApi: { reset: () => void }) => {
setLoginError(null);
try {
await API.authService.login(payload);
formApi.reset();
setIsAuthenticated(true);
const nextPath = normalizePath(searchParams.get('path'));
window.location.replace(nextPath);
} catch (error) {
if (axios.isAxiosError(error)) {
const axiosError = error as AxiosError<CommonErrorResponse>;
const problem = axiosError.response?.data;
if (problem) {
console.error('[LOGIN ERROR]', problem.errorCode, problem.detail);
setLoginError(getLoginErrorMessage(problem));
}
return;
}
console.error(error);
setLoginError('로그인에 실패했습니다. 다시 시도해주세요.');
}
};
return { handleLogin, loginError, clearLoginError };
};
|