🌵

useQueryWrapper 2022年ver

2022/10/09に公開

https://zenn.dev/brachio_takumi/articles/20210226-react-query#ラッパー用のカスタム-hooks-を作るべし

こちらの記事にて登場するWrapper関数を、以下のバージョン版でリライトして保存しておきます。

{
	"@tanstack/react-query": "^4.10.3",
	"axios": "^1.1.2",
}
useQueryWrapper.ts
import { QueryKey, useQuery, UseQueryOptions, UseQueryResult } from "@tanstack/react-query";
import axios, { AxiosResponse } from "axios";

type Props<T> = {
  queryKey?: string;
  deps?: QueryKey;
  options?: Omit<UseQueryOptions, "queryKey" | "queryFn" | "initialData">;
  req: () => Promise<AxiosResponse<T>>;
};

export const useQueryWrapper = <T>({
  queryKey,
  deps = [],
  options,
  req,
}: Props<T>): UseQueryResult<T> => {
  const k = Array.isArray(deps) ? [queryKey, ...deps] : [queryKey];
  return useQuery(
    k,
    async () => {
      try {
        const res = await req();
        return res.data;
      } catch (e) {
        if (axios.isAxiosError(e)) {
          throw e;
        } else {
          throw e;
        }
      }
    },
    options
  ) as UseQueryResult<T>;
};

useMutationWrapper.ts
import {
  MutationKey,
  useMutation,
  UseMutationOptions,
  UseMutationResult,
} from "@tanstack/react-query";
import axios, { AxiosResponse } from "axios";

type Props<T> = {
  mutationKey?: string;
  deps?: MutationKey;
  options?: Omit<UseMutationOptions, "mutationKey" | "mutationFn">;
  req: () => Promise<AxiosResponse<T>>;
};

export const useMutationWrapper = <T>({
  mutationKey,
  deps = [],
  options,
  req,
}: Props<T>): UseMutationResult<T> => {
  const k = Array.isArray(deps) ? [mutationKey, ...deps] : [mutationKey];

  return useMutation(
    k,
    async () => {
      try {
        const res = await req();
        return res.data;
      } catch (e) {
        if (axios.isAxiosError(e)) {
          throw e;
        } else {
          throw e;
        }
      }
    },
    options
  ) as UseMutationResult<T>;
};


Discussion