Skip to content

Commit 62b4cad

Browse files
committed
Add infinite query endpoint docs
1 parent 1bc4afd commit 62b4cad

File tree

4 files changed

+120
-5
lines changed

4 files changed

+120
-5
lines changed

docs/rtk-query/api/createApi.mdx

Lines changed: 82 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -148,6 +148,10 @@ See [Endpoint Definition Parameters](#endpoint-definition-parameters) for detail
148148
149149
#### Query endpoint definition
150150
151+
Query endpoints (defined with `builder.query()`) are used to cache data fetched from the server.
152+
153+
You must specify either a `query` field (which will use the API's `baseQuery` to make a request), or a `queryFn` function with your own async logic. All other fields are optional.
154+
151155
```ts title="Query endpoint definition" no-transpile
152156
export type QueryDefinition<
153157
QueryArg,
@@ -220,8 +224,70 @@ export type QueryDefinition<
220224
}
221225
```
222226
227+
#### Infinite Query endpoint definition
228+
229+
Infinite query endpoints (defined with `builder.infiniteQuery()`) are used to cache multi-page data sets from the server. They have all the same callbacks and options as standard query endpoints, but also require an additional [`infiniteQueryOptions`](#infinitequeryoptions) field to specify how to calculate the unique parameters to fetch each page.
230+
231+
For infinite query endpoints, there is a separation between the "query arg" used for the cache key, and the "page param" used to fetch a specific page. For example, a Pokemon API endpoint might have a string query arg like `"fire"` as the query arg, but use a page number as the param to determine which page to fetch out of the results. This means the page param is what will be passed to your `query` or `queryFn` methods.
232+
233+
```ts title="Infinite Query endpoint definition" no-transpile
234+
export type PageParamFunction<DataType, PageParam> = (
235+
firstPage: DataType,
236+
allPages: Array<DataType>,
237+
firstPageParam: PageParam,
238+
allPageParams: Array<PageParam>,
239+
) => PageParam | undefined | null
240+
241+
export type InfiniteQueryDefinition<
242+
QueryArg,
243+
PageParam,
244+
BaseQuery extends BaseQueryFn,
245+
TagTypes extends string,
246+
ResultType,
247+
ReducerPath extends string = string,
248+
> =
249+
// Infinite queries have all the same options as query endpoints,
250+
// but store the `{data, pages}` structure, and use the
251+
// `PageParam` type as the `QueryArg` for fetching.
252+
QueryDefinition<PageParam, BaseQuery, TagTypes, InfiniteData<ResultType>> & {
253+
/**
254+
* Required options to configure the infinite query behavior.
255+
* `initialPageParam` and `getNextPageParam` are required, to
256+
* ensure the infinite query can properly fetch the next page of data.
257+
* `initialPageparam` may be specified when using the
258+
* endpoint, to override the default value.
259+
*/
260+
infiniteQueryOptions: {
261+
/**
262+
* The initial page parameter to use for the first page fetch.
263+
*/
264+
initialPageParam: PageParam
265+
/**
266+
* If specified, only keep this many pages in cache at once.
267+
* If additional pages are fetched, older pages in the other
268+
* direction will be dropped from the cache.
269+
*/
270+
maxPages?: number
271+
/**
272+
* This function can be set to automatically get the previous cursor for infinite queries.
273+
* The result will also be used to determine the value of `hasPreviousPage`.
274+
*/
275+
getPreviousPageParam?: PageParamFunction<DataType, PageParam>
276+
/**
277+
* This function is required to automatically get the next cursor for infinite queries.
278+
* The result will also be used to determine the value of `hasNextPage`.
279+
*/
280+
getNextPageParam: PageParamFunction<DataType, PageParam>
281+
}
282+
}
283+
```
284+
223285
#### Mutation endpoint definition
224286
287+
Mutation endpoints (defined with `builder.mutation()`) are used to send updates to the server, and force invalidation and refetching of query endpoints.
288+
289+
As with queries, you must specify either the `query` option or the `queryFn` async method.
290+
225291
```ts title="Mutation endpoint definition" no-transpile
226292
export type MutationDefinition<
227293
QueryArg,
@@ -446,7 +512,7 @@ export interface BaseQueryApi {
446512
}
447513
```
448514

449-
#### queryFn function arguments
515+
#### `queryFn` function arguments
450516

451517
- `args` - The argument provided when the query itself is called
452518
- `api` - The `BaseQueryApi` object, containing `signal`, `dispatch` and `getState` properties
@@ -458,6 +524,21 @@ export interface BaseQueryApi {
458524

459525
[examples](docblock://query/endpointDefinitions.ts?token=EndpointDefinitionWithQueryFn.queryFn)
460526

527+
### `infiniteQueryOptions`
528+
529+
_(only for `infiniteQuery` endpoints)_
530+
531+
[summary](docblock://query/endpointDefinitions.ts?token=InfiniteQueryExtraOptions.infiniteQueryOptions)
532+
533+
The `infiniteQueryOptions` field includes:
534+
535+
- `initialPageParam`: the default page param value used for the first request, if this was not specified at the usage site
536+
- `maxPages`: an optional limit to how many fetched pages will be kept in the cache entry at a time
537+
- `getNextPageParam`: a required callback you must provide to calculate the next page param, given the existing cached pages and page params
538+
- `getPreviousPageParam`: an optional callback that will be used to calculate the previous page param, if you try to fetch backwards.
539+
540+
[examples](docblock://query/endpointDefinitions.ts?token=InfiniteQueryExtraOptions.infiniteQueryOptions)
541+
461542
### `transformResponse`
462543

463544
_(optional, not applicable with `queryFn`)_

packages/toolkit/src/query/createApi.ts

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -98,7 +98,7 @@ export interface CreateApiOptions<
9898
*/
9999
serializeQueryArgs?: SerializeQueryArgs<unknown>
100100
/**
101-
* Endpoints are a set of operations that you want to perform against your server. You define them as an object using the builder syntax. There are two basic endpoint types: [`query`](../../rtk-query/usage/queries) and [`mutation`](../../rtk-query/usage/mutations).
101+
* Endpoints are a set of operations that you want to perform against your server. You define them as an object using the builder syntax. There are three endpoint types: [`query`](../../rtk-query/usage/queries), [`infiniteQuery`](../../rtk-query/usage/infinite-queries) and [`mutation`](../../rtk-query/usage/mutations).
102102
*/
103103
endpoints(
104104
build: EndpointBuilder<BaseQuery, TagTypes, ReducerPath>,

packages/toolkit/src/query/endpointDefinitions.ts

Lines changed: 36 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -604,8 +604,42 @@ export interface InfiniteQueryExtraOptions<
604604
/**
605605
* Required options to configure the infinite query behavior.
606606
* `initialPageParam` and `getNextPageParam` are required, to
607-
* ensure the infinite query can properly fetch the next page of data. `initialPageparam` may be specified when using the
607+
* ensure the infinite query can properly fetch the next page of data.
608+
* `initialPageParam` may be specified when using the
608609
* endpoint, to override the default value.
610+
*
611+
* @example
612+
*
613+
* ```ts
614+
* // codeblock-meta title="infiniteQueryOptions example"
615+
* getInfinitePokemonWithMax: builder.infiniteQuery<
616+
Pokemon[],
617+
string,
618+
number
619+
>({
620+
infiniteQueryOptions: {
621+
initialPageParam: 0,
622+
maxPages: 3,
623+
getNextPageParam: (
624+
lastPage,
625+
allPages,
626+
lastPageParam,
627+
allPageParams,
628+
) => lastPageParam + 1,
629+
getPreviousPageParam: (
630+
firstPage,
631+
allPages,
632+
firstPageParam,
633+
allPageParams,
634+
) => {
635+
return firstPageParam > 0 ? firstPageParam - 1 : undefined
636+
},
637+
},
638+
query(pageParam) {
639+
return `https://example.com/listItems?page=${pageParam}`
640+
},
641+
}),
642+
* ```
609643
*/
610644
infiniteQueryOptions: InfiniteQueryConfigOptions<ResultType, PageParam>
611645

@@ -691,7 +725,7 @@ export type InfiniteQueryDefinition<
691725
ResultType,
692726
ReducerPath extends string = string,
693727
> =
694-
// Intentionally use `PageParam` as the QueryArg` type
728+
// Intentionally use `PageParam` as the `QueryArg` type
695729
BaseEndpointDefinition<PageParam, BaseQuery, ResultType> &
696730
InfiniteQueryExtraOptions<
697731
TagTypes,

packages/toolkit/src/query/react/buildHooks.ts

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -65,7 +65,7 @@ import { useStableQueryArgs } from './useSerializedStableValue'
6565
import { useShallowStableValue } from './useShallowStableValue'
6666
import type { InfiniteQueryDirection } from '../core/apiState'
6767
import { isInfiniteQueryDefinition } from '../endpointDefinitions'
68-
import { StartInfiniteQueryActionCreator } from '../core/buildInitiate'
68+
import type { StartInfiniteQueryActionCreator } from '../core/buildInitiate'
6969

7070
// Copy-pasted from React-Redux
7171
const canUseDOM = () =>

0 commit comments

Comments
 (0)