tanstack query
를 사용하였음└─ src
├─ apis
│ ├─ api
│ │ ├─ Auth
│ │ │ ├─ login.js
│ │ │ └─ useLogin.js
│ │ ├─ Category
│ │ │ └─ getCategory.js
│ │ ├─ Device
│ │ │ └─ getDevices.js
│ │ └─ User
│ │ ├─ getUser.js
│ │ └─ patchUser.js
│ ├─ services
│ │ └─ silentRefresh.js
│ └─ utils
│ ├─ axios.js
│ ├─ index.js
│ └─ queryClient.js
api
: api를 요청하고 응답 받는 API 함수services
: response 데이터를 정제 하는 함수utils
: 공통 함수async function getDevices(accessToken) {
const response = await axios.get(`${BASE_URL}/api/devices`, {
headers: {
Authorization: `Bearer ${accessToken}`,
},
});
return response.data;
}
async function getCategory(accessToken) {
const response = await axios.get(`${BASE_URL}/api/category`, {
headers: {
Authorization: `Bearer ${accessToken}`,
},
});
return response.data;
}
// utils\axios.js
import Axios from "axios";
import { BASE_URL } from "../../constants";
export const axios = Axios.create({
baseURL: BASE_URL,
});
axios.interceptors.request.use(
(config) => {
const accessToken = getToken();
config.headers["Authorization"] = `Bearer ${accessToken}`
return config;
},
(error) => {
return Promise.reject(error);
}
)
공통적으로 사용할 axios 인스턴스를 생성함
요청이 전달되기 전에 작업을 수행할 수 있는 interceptors
를 사용하여 header의 Authorization 필드에 accesstoken을 넣음
적용 후
import { axios } from "../../utils";
export async function getCategory(accessToken) {
const response = await axios.get("/category");
return response.data;
}
BASE_URL
은 환경변수로 관리하여 개발 환경과 배포 환경에서의 주소 변경을 수월하게 함// env.development
REACT_APP_HOME_URL=//222.222.222.222:22222/api
// env.production
REACT_APP_HOME_URL=//xxx.com/api
// constants\index.js
export * from "./api";
export * from "./token";
// constants\api.js
export const BASE_URL = process.env.REACT_APP_HOME_URL
// utils\queryClient.js
import { QueryClient } from "@tanstack/react-query";
export const queryClient = new QueryClient({
defaultOptions: {
queries: {
cacheTime: 600000, // (예시)
},
// ... 추가적으로 설정할 옵션들
},
});
QueryClientProvider
에 인자로 주면 됨import { queryClient } from "./apis/utils";
function App() {
return (
<QueryClientProvider client={queryClient}>
// ...
<Router />
</QueryClientProvider>
);
}
참고 :
https://ghost4551.tistory.com/163 (리팩토링_API 모듈 분리)
https://itchallenger.tistory.com/903 (Refactoring React: Separate API Layer)