Skip to content

Commit

Permalink
fix(types): make getQueryState types work with queryOptions (#7010)
Browse files Browse the repository at this point in the history
  • Loading branch information
TkDodo committed Mar 2, 2024
1 parent 0f10b26 commit 93d442c
Show file tree
Hide file tree
Showing 2 changed files with 25 additions and 4 deletions.
19 changes: 15 additions & 4 deletions packages/query-core/src/queryClient.ts
Original file line number Diff line number Diff line change
Expand Up @@ -204,11 +204,22 @@ export class QueryClient {
)
}

getQueryState<TQueryFnData = unknown, TError = DefaultError>(
queryKey: QueryKey,
): QueryState<TQueryFnData, TError> | undefined {
getQueryState<
TQueryFnData = unknown,
TError = DefaultError,
TTaggedQueryKey extends QueryKey = QueryKey,
TInferredQueryFnData = TTaggedQueryKey extends DataTag<
unknown,
infer TaggedValue
>
? TaggedValue
: TQueryFnData,
>(
queryKey: TTaggedQueryKey,
): QueryState<TInferredQueryFnData, TError> | undefined {
const options = this.defaultQueryOptions({ queryKey })
return this.#queryCache.get<TQueryFnData, TError>(options.queryHash)?.state
return this.#queryCache.get<TInferredQueryFnData, TError>(options.queryHash)
?.state
}

removeQueries(filters?: QueryFilters): void {
Expand Down
10 changes: 10 additions & 0 deletions packages/react-query/src/__tests__/queryOptions.test-d.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -108,6 +108,16 @@ describe('queryOptions', () => {
const data = queryClient.getQueryData(queryKey)
expectTypeOf(data).toEqualTypeOf<number | undefined>()
})
it('should return the proper type when passed to getQueryState', () => {
const { queryKey } = queryOptions({
queryKey: ['key'],
queryFn: () => Promise.resolve(5),
})

const queryClient = new QueryClient()
const state = queryClient.getQueryState(queryKey)
expectTypeOf(state?.data).toEqualTypeOf<number | undefined>()
})
it('should properly type updaterFn when passed to setQueryData', () => {
const { queryKey } = queryOptions({
queryKey: ['key'],
Expand Down

0 comments on commit 93d442c

Please sign in to comment.