-
Notifications
You must be signed in to change notification settings - Fork 3
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
[Feat/#155] react query 추가 #184
Merged
Merged
Changes from all commits
Commits
Show all changes
19 commits
Select commit
Hold shift + click to select a range
7055739
chore: react query 추가
pepperdad fa152fe
feat: queryClient 추가
pepperdad 2cd0160
remove: 필요없는 .gitkeep 제거
pepperdad b00c22a
Merge branch 'develop' of https://github.com/TEAM-BEAT/BEAT-Client in…
pepperdad 59eb74c
feat: instace 및 테스트 추가
pepperdad 6db2b41
feat: api 통신 테스트 추가
pepperdad 2f99a04
feat: token 관련 로직 추가
pepperdad bfad413
test: presignedUrl 테스트 코드 추가
pepperdad dfaa988
Merge branch 'develop' of https://github.com/TEAM-BEAT/BEAT-Client in…
pepperdad 306ca5f
Merge branch 'develop' of https://github.com/TEAM-BEAT/BEAT-Client in…
pepperdad 77a681f
fix: Chip 컴포넌트 에러 로그 수정
pepperdad 53753d1
feat: TokenRefresher 추가
pepperdad 5e9ed2f
fix: PerformanceCard 이미지 오류 수정
pepperdad 626b125
feat: 햄버거 닫는 로직 추가
pepperdad ec50fbc
feat: 모든 공연 정보 get api 추가
pepperdad 19cc801
feat: 메인 페이지 데이터 불러오는 로직 추가 및 타입 변경
pepperdad 2c55da9
feat: openapi-typescript 설정
pepperdad 44fee96
feat: useQuery 예시 코드 추가
pepperdad f7ffeb3
feat: useMutation 예시 코드 추가
pepperdad File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Empty file.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,47 @@ | ||
import { get, post } from "@apis/index"; | ||
import { components } from "@typings/api/schema"; | ||
import { ApiResponseType } from "@typings/commonType"; | ||
import { AxiosResponse } from "axios"; | ||
|
||
export interface postGuestReq { | ||
scheduleId: number; | ||
purchaseTicketCount: number; | ||
scheduleNumber: string; | ||
bookerName: string; | ||
bookerPhoneNumber: string; | ||
birthDate: string; | ||
password: string; | ||
totalPaymentAmount: number; | ||
isPaymentCompleted: boolean; | ||
} | ||
|
||
type GuestBookingResponse = components["schemas"]["GuestBookingResponse"]; | ||
|
||
// 1. API 요청 함수 작성 및 타입 추가 | ||
export const postGuestBook = async ( | ||
formData: postGuestReq | ||
): Promise<GuestBookingResponse | null> => { | ||
try { | ||
const response: AxiosResponse<ApiResponseType<GuestBookingResponse>> = await post( | ||
"/bookings/guest", | ||
formData | ||
); | ||
|
||
return response.data.data; | ||
} catch (error) { | ||
console.error("error", error); | ||
|
||
return null; | ||
} | ||
}; | ||
|
||
export const getGuestBookingList = async () => { | ||
try { | ||
const response = await get("/bookings/guest/retrieve"); | ||
|
||
console.log(response.data); | ||
return response; | ||
} catch (error) { | ||
console.error("error", error); | ||
} | ||
}; |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,28 @@ | ||
import { QueryClient, useMutation, useQuery } from "@tanstack/react-query"; | ||
import { getGuestBookingList, postGuestBook, postGuestReq } from "./api"; | ||
|
||
export const QUERY_KEY = { | ||
LIST: "list", | ||
}; | ||
|
||
// 2. 쿼리 작성 | ||
export const useGuestBook = () => { | ||
const queryClient = new QueryClient(); | ||
|
||
return useMutation({ | ||
mutationFn: (formData: postGuestReq) => postGuestBook(formData), // API 요청 함수 | ||
onSuccess: (res) => { | ||
// 성공 시, 호출 | ||
queryClient.invalidateQueries({ queryKey: [QUERY_KEY.LIST] }); | ||
}, | ||
}); | ||
}; | ||
|
||
export const useGetGuestBookingList = () => { | ||
return useQuery({ | ||
queryKey: [QUERY_KEY.LIST], | ||
queryFn: () => getGuestBookingList(), | ||
staleTime: 1000 * 60 * 60, | ||
gcTime: 1000 * 60 * 60 * 24, | ||
}); | ||
}; |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,18 @@ | ||
import { get } from "@apis/index"; | ||
import { components } from "@typings/api/schema"; | ||
import { ApiResponseType } from "@typings/commonType"; | ||
import { AxiosResponse } from "axios"; | ||
|
||
type HomeResponse = components["schemas"]["HomeResponse"]; | ||
|
||
// 1. API 요청 함수 작성 및 타입 추가 | ||
export const getAllScheduleList = async (): Promise<HomeResponse | null> => { | ||
try { | ||
const response: AxiosResponse<ApiResponseType<HomeResponse>> = await get("/main"); | ||
|
||
return response.data.data; | ||
} catch (error) { | ||
console.error("error", error); | ||
return null; | ||
Comment on lines
+8
to
+16
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. 1 |
||
} | ||
}; |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,16 @@ | ||
import { useQuery } from "@tanstack/react-query"; | ||
import { getAllScheduleList } from "./api"; | ||
|
||
const QUERY_KEY = { | ||
LIST: "list", | ||
}; | ||
|
||
// 2. 쿼리 작성 | ||
export const useGetAllScheduleList = () => { | ||
return useQuery({ | ||
queryKey: [QUERY_KEY.LIST], | ||
queryFn: () => getAllScheduleList(), // API 요청 함수 | ||
staleTime: 1000 * 60 * 60, | ||
gcTime: 1000 * 60 * 60 * 24, | ||
}); | ||
}; |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,32 @@ | ||
import { get } from "@apis/index"; | ||
import { useQuery } from "@tanstack/react-query"; | ||
|
||
export const QUERY_KEY_POST = { | ||
getPresignedUrl: "getPresignedUrl", | ||
}; | ||
|
||
interface PresignedUrlPropTypes { | ||
data: { fileName: string; url: string }; | ||
} | ||
|
||
const fetchPresignedUrl = async () => { | ||
try { | ||
const response = await get<PresignedUrlPropTypes>("/api/image/upload"); | ||
console.log(response.data); | ||
|
||
return response.data; | ||
} catch (err) { | ||
console.error("error", err); | ||
} | ||
}; | ||
|
||
export const usePresignedUrl = () => { | ||
const { data } = useQuery({ | ||
queryKey: [QUERY_KEY_POST.getPresignedUrl], | ||
queryFn: () => fetchPresignedUrl(), | ||
}); | ||
|
||
const fileName = data && data?.data?.fileName; | ||
const url = data && data?.data?.url; | ||
return { fileName, url }; | ||
}; |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,30 @@ | ||
import axios from "axios"; | ||
|
||
export const instance = axios.create({ | ||
baseURL: import.meta.env.VITE_API_BASE_URL, | ||
// withCredentials: true, | ||
|
||
headers: { | ||
Authorization: `Bearer ${localStorage.getItem("accessToken") || ""}`, | ||
}, | ||
}); | ||
|
||
export function get<T>(...args: Parameters<typeof instance.get>) { | ||
return instance.get<T>(...args); | ||
} | ||
|
||
export function post<T>(...args: Parameters<typeof instance.post>) { | ||
return instance.post<T>(...args); | ||
} | ||
|
||
export function put<T>(...args: Parameters<typeof instance.put>) { | ||
return instance.put<T>(...args); | ||
} | ||
|
||
export function patch<T>(...args: Parameters<typeof instance.patch>) { | ||
return instance.patch<T>(...args); | ||
} | ||
|
||
export function del<T>(...args: Parameters<typeof instance.delete>) { | ||
return instance.delete<T>(...args); | ||
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,77 @@ | ||
import { instance } from "@apis/index"; | ||
import { useEffect } from "react"; | ||
import { useNavigate } from "react-router-dom"; | ||
|
||
export default function TokenRefresher() { | ||
const navigate = useNavigate(); | ||
|
||
useEffect(() => { | ||
const interceptor = instance.interceptors.response.use( | ||
// 성공적인 응답 처리 | ||
(response) => { | ||
console.log("Starting Request", response); | ||
return response; | ||
}, | ||
async (error) => { | ||
const originalConfig = error.config; // 기존에 수행하려고 했던 작업 | ||
const msg = error.response.data.msg; // error msg from backend | ||
const status = error.response.status; // 현재 발생한 에러 코드 | ||
// access_token 재발급 | ||
|
||
if (status === 401) { | ||
if (msg === "Expired Access Token. 토큰이 만료되었습니다") { | ||
// console.log("토큰 재발급 요청"); | ||
await instance | ||
.post( | ||
"/users/refresh-token", | ||
{}, | ||
{ | ||
// TODO: 쿠키로 변경 ? | ||
headers: { | ||
Authorization: `${localStorage.getItem("Authorization")}`, | ||
Refresh: `${localStorage.getItem("Refresh")}`, | ||
}, | ||
} | ||
) | ||
.then((res) => { | ||
console.log("res: ", res); | ||
// 새 토큰 저장 | ||
localStorage.setItem("Authorization", res.headers.authorization); | ||
localStorage.setItem("Refresh", res.headers.refresh); | ||
|
||
// 새로 응답받은 데이터로 토큰 만료로 실패한 요청에 대한 인증 시도 (header에 토큰 담아 보낼 때 사용) | ||
originalConfig.headers["authorization"] = `Bearer ${res.headers.authorization}`; | ||
originalConfig.headers["refresh"] = res.headers.refresh; | ||
|
||
// console.log("New access token obtained."); | ||
// 새로운 토큰으로 재요청 | ||
return instance(originalConfig); | ||
}) | ||
.catch(() => { | ||
console.error("An error occurred while refreshing the token:", error); | ||
}); | ||
} | ||
// refresh_token 재발급과 예외 처리 | ||
// else if(msg == "만료된 리프레시 토큰입니다") { | ||
else { | ||
localStorage.clear(); | ||
navigate("/main"); | ||
alert("토큰이 만료되어 자동으로 로그아웃 되었습니다."); | ||
} | ||
} else if (status === 400 || status === 404 || status === 409) { | ||
console.log("hi3"); | ||
// window.alert(msg); | ||
// console.log(msg) | ||
} | ||
// console.error('Error response:', error); | ||
// 다른 모든 오류를 거부하고 처리 | ||
return Promise.reject(error); | ||
} | ||
); | ||
return () => { | ||
instance.interceptors.response.eject(interceptor); | ||
}; | ||
}, []); | ||
|
||
return <></>; | ||
} |
Oops, something went wrong.
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
2