Refactor Login component
Splits the Login component into smaller, more manageable parts and extracts related logic into hooks to improve code organization and readability.
This commit is contained in:
87
src/hooks/useLogin.ts
Normal file
87
src/hooks/useLogin.ts
Normal file
@@ -0,0 +1,87 @@
|
||||
|
||||
import { useState } from "react";
|
||||
import { useNavigate } from "react-router-dom";
|
||||
import { useToast } from "@/hooks/useToast.wrapper";
|
||||
import { useAuth } from "@/contexts/auth";
|
||||
|
||||
export function useLogin() {
|
||||
const [email, setEmail] = useState("");
|
||||
const [password, setPassword] = useState("");
|
||||
const [showPassword, setShowPassword] = useState(false);
|
||||
const [isLoading, setIsLoading] = useState(false);
|
||||
const [loginError, setLoginError] = useState<string | null>(null);
|
||||
const navigate = useNavigate();
|
||||
const { toast } = useToast();
|
||||
const { signIn } = useAuth();
|
||||
|
||||
const handleLogin = async (e: React.FormEvent) => {
|
||||
e.preventDefault();
|
||||
setLoginError(null);
|
||||
|
||||
if (!email || !password) {
|
||||
toast({
|
||||
title: "입력 오류",
|
||||
description: "이메일과 비밀번호를 모두 입력해주세요.",
|
||||
variant: "destructive"
|
||||
});
|
||||
return;
|
||||
}
|
||||
|
||||
setIsLoading(true);
|
||||
|
||||
try {
|
||||
const { error } = await signIn(email, password);
|
||||
|
||||
if (error) {
|
||||
console.error("로그인 실패:", error);
|
||||
let errorMessage = "로그인에 실패했습니다.";
|
||||
|
||||
// Supabase 오류 메시지 처리
|
||||
if (error.message) {
|
||||
if (error.message.includes("Invalid login credentials")) {
|
||||
errorMessage = "이메일 또는 비밀번호가 올바르지 않습니다.";
|
||||
} else if (error.message.includes("Email not confirmed")) {
|
||||
errorMessage = "이메일 인증이 완료되지 않았습니다. 이메일을 확인해주세요.";
|
||||
} else {
|
||||
errorMessage = `오류: ${error.message}`;
|
||||
}
|
||||
}
|
||||
|
||||
setLoginError(errorMessage);
|
||||
|
||||
toast({
|
||||
title: "로그인 실패",
|
||||
description: errorMessage,
|
||||
variant: "destructive"
|
||||
});
|
||||
} else {
|
||||
navigate("/");
|
||||
}
|
||||
} catch (err: any) {
|
||||
console.error("로그인 과정에서 예외 발생:", err);
|
||||
const errorMessage = err.message || "알 수 없는 오류가 발생했습니다.";
|
||||
setLoginError(errorMessage);
|
||||
|
||||
toast({
|
||||
title: "로그인 오류",
|
||||
description: errorMessage,
|
||||
variant: "destructive"
|
||||
});
|
||||
} finally {
|
||||
setIsLoading(false);
|
||||
}
|
||||
};
|
||||
|
||||
return {
|
||||
email,
|
||||
setEmail,
|
||||
password,
|
||||
setPassword,
|
||||
showPassword,
|
||||
setShowPassword,
|
||||
isLoading,
|
||||
loginError,
|
||||
setLoginError,
|
||||
handleLogin
|
||||
};
|
||||
}
|
||||
Reference in New Issue
Block a user