Skip to content

Commit

Permalink
feat: 새로고침할 경우 refresh 요청 보내도록
Browse files Browse the repository at this point in the history
  • Loading branch information
pipisebastian committed Nov 20, 2024
1 parent 05b84a8 commit 819bf6c
Show file tree
Hide file tree
Showing 2 changed files with 18 additions and 22 deletions.
14 changes: 7 additions & 7 deletions client/src/App.tsx
Original file line number Diff line number Diff line change
@@ -1,17 +1,17 @@
import { useEffect } from "react";
import { WorkSpace } from "@features/workSpace/WorkSpace";
import { useRefreshMutation } from "./apis/auth";
import { useRefreshQuery } from "./apis/auth";
import { useUserInfo } from "./stores/useUserStore";

const App = () => {
// TODO 라우터, react query 설정
const { id } = useUserInfo();
const { mutate: refreshToken } = useRefreshMutation();
const { id, name, accessToken } = useUserInfo();
const { refetch: refreshToken } = useRefreshQuery();

useEffect(() => {
// 세션 스토리지에 정보가 있을 경우 토큰 갱신
if (id) refreshToken();
}, [id]);
if (id && name && !accessToken) {
refreshToken();
}
}, []);

return (
<>
Expand Down
26 changes: 11 additions & 15 deletions client/src/apis/auth.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import { useMutation } from "@tanstack/react-query";
import { useMutation, useQuery } from "@tanstack/react-query";
import { useUserActions } from "@src/stores/useUserStore";
import { unAuthorizationFetch, fetch } from "./axios";

Expand Down Expand Up @@ -34,6 +34,7 @@ export const useLoginMutation = (onSuccess: () => void) => {
mutationFn: fetcher,
onSuccess: (response) => {
const { id, name, accessToken } = response.data;
console.log(accessToken);
setUserInfo(id, name, accessToken);
onSuccess();
},
Expand All @@ -56,23 +57,18 @@ export const useLogoutMutation = (onSuccess: () => void) => {
});
};

export const useRefreshMutation = () => {
const { updateAccessToken, removeUserInfo } = useUserActions();
export const useRefreshQuery = () => {
const { updateAccessToken } = useUserActions();

const fetcher = () => {
// TODO 추후 그냥 fetch로 변경 (access token 넣어줘야함)
return unAuthorizationFetch.post("/auth/refresh");
// return fetch.post("/auth/refresh"); // refresh token은 알아서 보내질거임
};

return useMutation({
mutationFn: fetcher,
onSuccess: (response) => {
return useQuery({
queryKey: ["refresh"],
queryFn: () => fetch.get("/auth/refresh"),
enabled: false,
select: (response) => {
const { accessToken } = response.data;
console.log(accessToken);
updateAccessToken(accessToken);
},
onError: () => {
removeUserInfo();
return response.data;
},
});
};

0 comments on commit 819bf6c

Please sign in to comment.