호텔 앱에서 API 연동 시 React-Query를 활용 한 커스텀 훅으로 만들어, 각 컴포넌트에서 상태 관리하기 용이하도록 만들었습니다.

  1. Axios 인스턴스 설정

    import axios from "axios";
    
    const instance = axios.create({
    	validateStatus: status => status < 500,
    });
    
    instance.interceptors.request.use(
    	config => {
    		return config;
    	},
    	error => Promise.reject(error),
    );
    
    instance.interceptors.response.use(
    	async response => {
    		if ([204, 304].indexOf(response.status) > -1) {
          return response;
        } else {
          return !response ? null : response.data;
        }
    	},
    	async error => {
    		return Promise.reject(error);
    	},
    );
    
    export default instance;
    
  2. useRequest 생성

    import {AxiosError, AxiosRequestConfig} from "axios";
    import {useQuery, UseQueryOptions} from "@tanstack/react-query";
    import useConfigureAxios from "@FRAMEWORK/utils/useConfigureAxios";
    
    interface Response<T> {
    	... // response 규격
    }
    
    const useRequest = <T>(querykey: string[], config: AxiosRequestConfig, options: UseQueryOptions = {}) => {
    	config.url = `/${config.url}`;
    	return useQuery<Response<T>, AxiosError>(querykey, () => useConfigureAxios(config).then(r => r.data), options);
    };
    
    export default useRequest;
    
  3. useCalendar 생성

    type Day = {
    	...
    };
    
    type Days = {
    	...
    };
    
    interface Calendar {
    	...
    }
    
    const getPath = (): string | null => `/calendar`;
    
    const useCalendar = <U>(countryCode: string, itemCategoryCode: string, options?: UseQueryOptions) => {
    	const axiosConfig: AxiosRequestConfig = {
    			...
    		};
        return useRequest<U extends Calendar ? U : Calendar>([key, countryCode, itemCategoryCode, getPath()], axiosConfig, {
            staleTime: 1000 * 60 * 1,
            cacheTime: 1000 * 60 * 1,
            ...options,
        });
    };