graphql-code-generator-community icon indicating copy to clipboard operation
graphql-code-generator-community copied to clipboard

Support of @tanstack/react-query's `useQueries` hook

Open liitfr opened this issue 2 years ago • 4 comments

Is your feature request related to a problem? Please describe.

I would like to use @tanstack/react-query's useQueries`` hook but I realized it's not supported by @graphql-codegen/typescript-react-query.

Problem is detailed on this stackoverflow question :

Describe the solution you'd like

I wish @graphql-codegen/typescript-react-query generates hooks that allow us to run parallel queries

Describe alternatives you've considered

For now : here is my current workaround :

import { useQueries, UseQueryOptions } from '@tanstack/react-query';
import { GraphQLClient } from 'graphql-request';

import {
  GetOneStuffDocument,
  GetOneStuffQuery,
  GetOneStuffQueryVariables,
  Scalars,
} from '@foo/data-access';

function fetcher<TData, TVariables>(
  client: GraphQLClient,
  query: string,
  variables?: TVariables,
  headers?: RequestInit['headers']
) {
  return async (): Promise<TData> =>
    client.request<TData, TVariables>(query, variables, headers);
}

export const useGetSomeStuffQuery = <
  TData = GetOneStuffQuery,
  TError = unknown
>(
  client: GraphQLClient,
  variables: { ids: Scalars['MongoObjectId'][] },
  options?: UseQueryOptions<GetOneStuffQuery, TError, TData>,
  headers?: RequestInit['headers']
) =>
  useQueries({
    queries: variables.ids.map((id) => ({
      queryKey: ['GetSomeStuff', id],
      queryFn: fetcher<
        GetOneStuffQuery,
        GetOneStuffQueryVariables
      >(client, GetOneStuffDocument, { id }, headers),
      options,
    })),
  });

Additional context

liitfr avatar Nov 09 '22 11:11 liitfr