Skip to content

Commit 06833ba

Browse files
committed
fix: add ability to type the query key in the query function context
1 parent f0d32ca commit 06833ba

File tree

3 files changed

+21
-7
lines changed

3 files changed

+21
-7
lines changed

docs/src/pages/guides/query-functions.md

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -55,7 +55,7 @@ function Todos({ completed }) {
5555

5656
// Access the key, status and page variables in your query function!
5757
function fetchTodoList({ queryKey }) {
58-
const { status, page } = queryKey[1]
58+
const [_key, { status, page }] = queryKey
5959
return new Promise()
6060
}
6161
```

src/core/types.ts

Lines changed: 5 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -9,8 +9,11 @@ export type QueryFunction<T = unknown> = (
99
context: QueryFunctionContext
1010
) => T | Promise<T>
1111

12-
export interface QueryFunctionContext<TPageParam = any> {
13-
queryKey: QueryKey
12+
export interface QueryFunctionContext<
13+
TQueryKey extends QueryKey = QueryKey,
14+
TPageParam = any
15+
> {
16+
queryKey: TQueryKey
1417
pageParam?: TPageParam
1518
}
1619

src/react/tests/useQuery.test.tsx

Lines changed: 15 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -10,7 +10,13 @@ import {
1010
renderWithClient,
1111
setActTimeout,
1212
} from './utils'
13-
import { useQuery, QueryClient, UseQueryResult, QueryCache } from '../..'
13+
import {
14+
useQuery,
15+
QueryClient,
16+
UseQueryResult,
17+
QueryCache,
18+
QueryFunctionContext,
19+
} from '../..'
1420

1521
describe('useQuery', () => {
1622
const queryCache = new QueryCache()
@@ -1666,10 +1672,15 @@ describe('useQuery', () => {
16661672
// See https://github.com/tannerlinsley/react-query/issues/147
16671673
it('should not pass stringified variables to query function', async () => {
16681674
const key = queryKey()
1669-
const queryFn = jest.fn()
1670-
queryFn.mockImplementation(() => sleep(10))
1671-
16721675
const variables = { number: 5, boolean: false, object: {}, array: [] }
1676+
const queryFn = jest
1677+
.fn()
1678+
.mockImplementation(
1679+
async (ctx: QueryFunctionContext<[string, typeof variables]>) => {
1680+
await sleep(10)
1681+
return ctx.queryKey
1682+
}
1683+
)
16731684

16741685
function Page() {
16751686
useQuery([key, variables], queryFn)

0 commit comments

Comments
 (0)