graphql-code-generator-community
graphql-code-generator-community copied to clipboard
[react-query] query keys for queries with no required variables are different with {} vs. no arguments
Which packages are impacted by your issue?
@graphql-codegen/typescript-react-query
Describe the bug
If a query does not have any required arguments, then the codegen plugin currently generates a hook that looks like this:
export const useDummyQuery = <
...
queryKey: variables === undefined ? ['Dummy'] : ['Dummy', variables]
...
// exposeQueryKeys:
useDummyQuery.getKey = (variables?: DummyQueryVariables) => variables === undefined ? ['Dummy'] : ['Dummy', variables]
This ends up causing some confusion in the code. For example, useDummyQuery() will have a unique entry in the react-query cache compared to useDummyQuery({}). This also causes issues with query invalidation, since the key used to invalidate needs to match:
const { data, ... } = useDummyQuery()
// elsewhere:
queryClient.invalidateQueries({ queryKey: useDummyQuery.getKey({}) }) // does not invalidate the above
Proposed solution:
If we default the query variable to an empty object then it should work as expected:
useDummyQuery.getKey = (variables?: DummyQueryVariables) => variables === undefined ? ['Dummy', {}] : ['Dummy', variables]
This may be a breaking change if users were invalidating based on exact query key matches without using the .getKey helper, although that seems unlikely:
// Technically this will no longer work
queryClient.invalidateQueries({ queryKey: ['Dummy'], exact: true })
Your Example Website or App
none
Steps to Reproduce the Bug or Issue
- Use graphQL Codegen with a query that takes no arguments. Make sure
exposeQueryKeysis enabled. - When fetching data, use
const { data } = useSomeQuery()without brackets - Have another button that invalidates the query with
queryClient.invalidateQueries({ queryKey: useSomeQuery.getKey({}) })with brackets
Notice tha this does not re-fetch the data.
Expected behavior
I would expect the query invalidation to force a refetch of the data
Screenshots or Videos
No response
Platform
- OS: macOS
- NodeJS: 18.17.1
graphqlversion: 16.8.0@graphql-codegen/typescript-react-queryversion(s): 6.1.0
Codegen Config File
---
schema:
- https://.../graphql:
headers:
apikey: ...
documents: ./src/**/*.graphql
config:
strictScalars: true
enumsAsConst: true
reactQueryVersion: 5
scalars:
...
generates:
./src/generated/types.ts:
plugins:
- add:
content: //@ts-nocheck
- typescript
- typescript-operations
- typescript-react-query:
fetcher: ...
addInfiniteQuery: true
exposeQueryKeys: true
exposeFetcher: true
errorType: Error
Additional context
No response
watching this issue as I experienced similar