dotansimha / dotansimha/graphql-code-generator
How can we add options to the useQuery helper with the client preset?
- Dominant language
- TypeScript
- Stars
- 11.3k
- Forks
- 1.4k
- Avg merge
- 1d 1h
- Merged PRs (30d)
- 23
Description
### Is your feature request related to a problem? Please describe.
The helper found below, has been used in the docs to use graphql-codegen together with @tanstack/query. (preset: client)
However, the helper does not seem to play nice when trying to add options to the function signature (of type `UseQueryOptions`) and gives a type error when doing this.
I am happy to update the documentation afterwards, since I think this is used quite commonly.
In addition to this, I think the documentation should also provide examples for `useSuspenseQuery` and `useInfiniteQuery`.
This is the slightly modified helper, using a `graphql-request` client:
```typescript
export function useGraphQL(
document: TypedDocumentNode,
...[variables]: TVariables extends Record ? [] : [TVariables]
): UseQueryResult {
const client = useGraphqlClient()
return useQuery([(document.definitions[0] as any).name.value, variables], () =>
client.request(
document,
queryKey[1] ? queryKey[1] : undefined
),
)
}
```
I've tried to achieve adding options with the following snippet:
```typescript
export default function useGraphQL(
document: TypedDocumentNode,
variables: TVariables extends Record ? [] : [TVariables],
options: Omit, 'queryKey'>
) {
const client = useGraphqlClient()
return useQuery({
...options,
queryKey: [(document.definitions[0] as any).name.value, variables],
queryFn: async ({ queryKey }) =>
client.request(
document,
queryKey[1] ? queryKey[1] : undefined // Typescript Error here
),
})
}
```
But this results in the following error on the second parameter of `request()`
```
Argument of type '{} | undefined' is not assignable to parameter of type 'Variables | undefined'.
Type '{}' is not assignable to type 'Variables'.
Index signature for type 'string' is missing in type '{}'.ts(2345)
```
codegen.ts
```ts
const config: CodegenConfig = {
schema: 'http://localhost:3000/graphql',
documents: ['../../apps/web/**/*.tsx', '../../apps/web/**/*.ts'],
generates: {
'./graphql/': {
preset: 'client',
},
},
}
```
### Describe the solution you'd like
Adding more examples to the docs.
### Describe alternatives you've considered
_No response_
### Is your feature request related to a problem? Please describe.
_No response_
Contributor guide
No contributing guide indexed for this repository
Assessment
This issue has not been assessed yet.