http method에 관한 유틸함수를 생성하여 각 API 요청을 훅에서 바로 사용할 수 있도록 하여 코드 효율성을 높였습니다.
import axiosInstance from '@/lib/axiosInstance';
export async function GET<T>(url: string): Promise<T> {
try {
const response = await axiosInstance.get(url);
return response.data;
} catch (error) {
throw new Error(error instanceof Error ? error.message : String(error));
}
}
export async function POST<T, U>(url: string, data?: U): Promise<T> {
try {
const response = await axiosInstance.post(url, data);
return response.data;
} catch (error) {
throw new Error(error instanceof Error ? error.message : String(error));
}
}
export async function PUT<T, U>(url: string, data: U): Promise<T> {
try {
const response = await axiosInstance.put(url, data);
return response.data;
} catch (error) {
throw new Error(error instanceof Error ? error.message : String(error));
}
}
export async function DELETE<T>(url: string): Promise<T> {
try {
const response = await axiosInstance.delete(url);
return response.data;
} catch (error) {
throw new Error(error instanceof Error ? error.message : String(error));
}
}
따라서 api 함수를 따로 만들지 않아도 hooks에서 한번에 api 함수를 처리할 수 있어서 코드 재사용성 증가, 코드 가독성 향상, 코드의 유지보수 용이의 효과를 얻을 수 있었다.
또한 코드 중복 제거와 간소화로 번들 크기를 간접적으로 줄이는 효과를 얻었습니다.
hooks 작성 예시
import { useQuery, UseQueryOptions } from '@tanstack/react-query';
import { AxiosError } from 'axios';
import { GET } from '@/apis/services/httpMethod';
import { API_ENDPOINTS } from '@/constants/ApiEndpoints';
import { QUERY_KEYS } from '@/constants/QueryKeys';
import { BaseResponse } from '@/types/response';
interface UserResponse {
email: string;
name: string;
profilePic: string;
}
interface UserInfoResponse extends BaseResponse {
data: UserResponse;
}
const userInfoOptions: UseQueryOptions<UserInfoResponse, AxiosError> = {
queryKey: [QUERY_KEYS.USER_INFO],
queryFn: () => GET<UserInfoResponse>(API_ENDPOINTS.AUTH.USER),
};
export const useUserQuery = () => {
const { data, ...etc } = useQuery(userInfoOptions);
const email = data?.data.email ?? '';
const name = data?.data.name ?? '';
const profile = data?.data.profilePic ?? '';
return { email, name, profile, ...etc };
};
현재 프로젝트에서는 해당 메소드 유틸함수를 안쓴 hooks가 부분 있어서 리팩토링 중에 있습니다.