Skip to content

[react-query] Support queryOptions when reactQueryVersion 5 or above is used #875

@rliljest

Description

@rliljest

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

react-query v5 introduced the query options API, and currently there is no way to have graphql codegen generate those options for us

Describe the solution you'd like

In a similar way that we currently have exposeQueryKeys and exposeFetcher, I think we should have an exposeQueryOptions config. This should only be valid if we are on reactQueryVersion 5 or higher.

This could generate something like the following:

import { queryOptions, ... } from '@tanstack/react-query'

useDemoQuery.options = (variables: DemoQueryVariables) => queryOptions({
  queryKey: ['Demo', variables],
  queryFn: someFetcher<DemoQuery, DemoQueryVariables>(DemoDocument, variables)
})

If you are just using the generated hook to get data, e.g. const { data, ... } = useDemoQuery(...), nothing has changed. This does greatly simplify other react-query APIs:

useQueries({
  queries: [useDemoQuery.options(...), ...]
})
queryClient.prefetchQuery(useDemoQuery.options(...))
queryClient.setQueryData(useDemoQuery.options(...).queryKey, ...)
const cachedData = queryClient.getQueryData(...).queryKey)

NOTE: It may seem unnecessary to get the .queryKey from these options, when you could enable exposeQueryKeys and get the keys from there. The main difference is that internally, react-query adds a TypeScript DataTag to the key when it's generated from queryOptions, which gives the key type knowledge about the data it represents. So in the above example, both the setQueryData and getQueryData calls have automatic type safety, without having to explicitly pull in the generated DemoQuery type and passing it to a generic.

Describe alternatives you've considered

It is technically possible to use the DataTag type from react-query directly, and use that with the existing .getKey option to get the same affect. The only potential concern is that, although exported from the react-query package, I cannot find any documentation on the react-query site that mentions it. So it might be considered part of a private API and might change in the future.

We could also use queryOptions ourselves, but this is tedious if we want to enable it for all of our queries.

Although I haven't explored it, there is also infiniteQueryOptions which may be used when addInfiniteQuery is used

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions