Skip to content

Commit 408d13f

Browse files
authored
Merge pull request #19 from moonhuicheol/feature/login
✨ feat: loginUser axios함수 구현
2 parents f10ac28 + e3111e0 commit 408d13f

6 files changed

Lines changed: 93 additions & 8 deletions

File tree

src/api/axios.ts

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,7 @@
11
import axios from "axios";
22

33
export const instance = axios.create({
4-
baseURL: import.meta.env.VITE_BASE_URL,
4+
baseURL: "https://api.davincicodegame.store",
55
});
66

77
export const authInstance = axios.create({

src/api/userAuthApi.ts

Lines changed: 56 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,56 @@
1+
import { authInstance, instance } from "./axios";
2+
import { AxiosError } from "axios";
3+
4+
export interface ILoginResponse {
5+
accessToken: string;
6+
}
7+
8+
export interface IErrorResponse {
9+
status: number;
10+
message: string;
11+
}
12+
13+
export const loginUser = async (logInfo: {
14+
userEmail: string;
15+
password: string;
16+
}): Promise<ILoginResponse> => {
17+
try {
18+
console.log(instance, "인스턴스확인");
19+
const response = await instance.post<ILoginResponse>(
20+
"/auth/login",
21+
logInfo,
22+
{
23+
withCredentials: true,
24+
headers: {
25+
"Content-Type": "application/json",
26+
},
27+
},
28+
);
29+
30+
console.log(response);
31+
return response.data;
32+
} catch (error) {
33+
const axiosError = error as AxiosError<IErrorResponse>;
34+
if (axiosError.response) {
35+
console.log(axiosError.response.data.status);
36+
throw new Error(axiosError.response.data.message); // 에러 메시지 던지기
37+
} else {
38+
throw new Error("로그인 중 예상치 못한 오류가 발생했습니다.");
39+
}
40+
}
41+
};
42+
43+
export const refreshToken = async () => {
44+
try {
45+
const response = await authInstance.post("/auth/refresh", {
46+
withCredentials: true,
47+
});
48+
console.log(response);
49+
const accessToken = response?.headers.authorization;
50+
51+
localStorage.setItem("accessToken", accessToken);
52+
return response.data.accessToken;
53+
} catch (err) {
54+
console.log(err);
55+
}
56+
};

src/hooks/useMutation.tsx

Lines changed: 25 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -6,6 +6,7 @@ import {
66
joinGameRoom,
77
outGameRoom,
88
} from "../api/gameRoomApi";
9+
import { ILoginResponse, loginUser } from "../api/userAuthApi";
910

1011
export const useCreateRoomMutation = () => {
1112
const navigate = useNavigate();
@@ -14,7 +15,7 @@ export const useCreateRoomMutation = () => {
1415
return useMutation<ICreateGameRoomResponse, Error, { roomName: string }>({
1516
mutationFn: createGameRoom,
1617
onSuccess: (data) => {
17-
navigate(`/gameRoom/${data.room.id}`);
18+
navigate(`/game/room/${data.room.id}`);
1819
queryClient.invalidateQueries({
1920
queryKey: ["gameRoomList"],
2021
});
@@ -45,11 +46,16 @@ export const useJoinRoomMutation = () => {
4546

4647
export const useOutRoomMutaion = () => {
4748
const navigate = useNavigate();
49+
const queryClient = useQueryClient();
50+
4851
return useMutation({
4952
mutationFn: outGameRoom,
5053
onSuccess: (data) => {
5154
console.log("방나가기 성공", data);
5255
navigate("/game");
56+
queryClient.invalidateQueries({
57+
queryKey: ["gameRoomList"],
58+
});
5359
},
5460

5561
onError: (error: any) => {
@@ -63,3 +69,21 @@ export const useOutRoomMutaion = () => {
6369
},
6470
});
6571
};
72+
73+
export const useLoginSubmitMutation = () => {
74+
return useMutation<
75+
ILoginResponse,
76+
Error,
77+
{ userEmail: string; password: string }
78+
>({
79+
mutationFn: loginUser,
80+
onSuccess: (data) => {
81+
console.log(data);
82+
const accessToken = data?.accessToken;
83+
localStorage.setItem("accessToken", accessToken);
84+
},
85+
onError: (error) => {
86+
alert(error.message);
87+
},
88+
});
89+
};

src/pages/user/login/Login.tsx

Lines changed: 8 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -4,16 +4,21 @@ import Button from "../../../components/ui/button/Button";
44
import { loginSchema, schema } from "./schema";
55
import Input from "../../../components/ui/input/Input";
66
import * as S from "./loginStyle2";
7+
import { useLoginSubmitMutation } from "../../../hooks/useMutation";
78

89
export default function LoginPage() {
910
const methods = useForm<loginSchema>({
1011
resolver: zodResolver(schema),
1112
mode: "onChange",
1213
});
1314

15+
const mutation = useLoginSubmitMutation();
16+
1417
const onClickSubmit = async (data: loginSchema) => {
15-
console.log(data);
18+
const result = mutation.mutate(data);
19+
console.log(result);
1620
};
21+
1722
return (
1823
<>
1924
<S.container>
@@ -23,9 +28,9 @@ export default function LoginPage() {
2328
<S.form onSubmit={methods.handleSubmit(onClickSubmit)}>
2429
<S.inputBox>
2530
<S.label>이메일</S.label>
26-
<Input<loginSchema> type="text" keyname="email" />
31+
<Input<loginSchema> type="text" keyname="userEmail" />
2732
<S.errorMessage>
28-
{methods.formState.errors.email?.message}
33+
{methods.formState.errors.userEmail?.message}
2934
</S.errorMessage>
3035
</S.inputBox>
3136
<S.inputBox>

src/pages/user/login/schema.ts

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,13 +1,13 @@
11
import { z } from "zod";
22

33
export const schema: z.ZodType<loginSchema> = z.object({
4-
email: z.string().email("이메일 형식이 아닙니다."),
4+
userEmail: z.string(),
55
password: z
66
.string()
77
.min(4, { message: "비밀번호는 최소 4자리 이상 입력해주세요." }),
88
});
99

1010
export interface loginSchema {
11-
email: string;
11+
userEmail: string;
1212
password: string;
1313
}

src/routes/router.tsx

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -35,7 +35,7 @@ export const router = createBrowserRouter([
3535
element: <GameRoomList />,
3636
},
3737
{
38-
path: "/room/:id",
38+
path: "room/:id",
3939
element: <GameRoom />,
4040
},
4141
],

0 commit comments

Comments
 (0)