FE/React & TS

[TS] useQuery 커스텀 훅 사용하기

yeahzzz 2024. 7. 21. 18:48

❓UseQueryOptions

UseQueryOptionsreact-query의 useQuery 훅에서 쿼리의 동작을 제어하는 옵션을 정의하는 타입이다.

이 타입을 사용하여 쿼리의 캐싱, 데이터 재검증, 에러 핸들링, 리트라이 로직 등 다양한 동작을 설정할 수 있다.

 

UseQueryOptions 타입을 사용할 때 react-query에서 총 네 가지 타입 인수를 받는다.

  1. TData: 쿼리에서 반환되는 데이터 타입
  2. TError: 쿼리에서 반환되는 에러 타입
  3. TResult: select 함수를 사용한 후의 데이터 타입 (기본적으로 TData와 동일함)
  4. TQueryKey: 쿼리 키의 타입
export const useProductDetailsQuery = (
  productId: number,
  options?: UseQueryOptions<ProductDetailsData>, //경우에 따라 AxiosError도 추가하자.
): UseQueryResult<ProductDetailsData> => {
  return useQuery({
    queryKey: queryKeys.detailsByProductId(productId),
    queryFn: () => getProductDetails(productId),
    ...options,
  });
};

❗참고) 리액트쿼리 v5에서는 useQuery에서 options 대신 …options를 사용해도록 바뀌었다. 참고

 

나는 여러 쿼리 키를 사용할 예정이라서 queryKeys 함수를 별도로 작성해주었다.

export const queryKeys = {
  detailsByProductId: (productId: number) => ['productDetails', productId],
};

사용 예제

const { data, isLoading } = useProductDetailsQuery(productId);
const { data, isLoading } = useProductDetailsQuery(productId, {
  queryKey: queryKeys.detailsByProductId(productId),
  staleTime: 6000,
});
옵션을 지정해줄 때 queryKey가 없다는 에러가 계속 떴다.
useProductDetailsQuery에서 queryKey를 정의해주거나, UseQueryOptions의 타입에서 Omit 메서드로 queryKey를 삭제해주니 잘 작동되었다.