dotansimha / dotansimha/graphql-code-generator-community

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

Open
#875 5 comments 6 reactions 0 assignees View on GitHub
Dominant language
TypeScript
Stars
137
Forks
195
Avg merge
6h 20m
Merged PRs (30d)
16

Description

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

react-query v5 introduced the [query options API](https://tanstack.com/query/latest/docs/framework/react/guides/query-options), 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:

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

useDemoQuery.options = (variables: DemoQueryVariables) => queryOptions({
queryKey: ['Demo', variables],
queryFn: someFetcher(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:

```ts
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

Contributor guide

No contributing guide indexed for this repository

Assessment

This issue has not been assessed yet.

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.