React Query Composition

Created
May 12, 2022 12:50 PM
Tags
import { AxiosError, AxiosResponse } from "axios";
import { useQuery, UseQueryOptions } from "react-query";
import axios from "axios";

import {
  IDetailDataRequest,
  IDetailDataResponse,
} from "@/models/detailData";

// fetcher function
async function getDetailData(
  payload: IDetailDataRequest
) {
  const { data }: AxiosResponse<IDetailDataResponse> =
    await axios.get(
      `/api/{detail-data-path}`, {
				// Headers and options....
			}
    );

  return data;
}

// query function
function useGetDetailData(
  payload: IDetailDataRequest,
  options?: Omit<
    UseQueryOptions<
      IDetailDataResponse,
      AxiosError,
      IDetailDataResponse
    >,
    "queryKey"
  >
) {
  return useQuery<
    IDetailDataResponse,
    AxiosError,
    IDetailDataResponse
  >(
    ["{queryKey}"], // Adjust query key
    () => getDetailData(payload),
    options
  );
}