Skip to content

Commit 29bea2a

Browse files
authored
Assorted pre-2.8 docs tweaks (#4968)
* Fix ancient obsolete docs links * Better describe tag functions * Fix page param arg names by inlining declarations * Add note on selectFromResult * Flesh out Code Splitting usage guide page
1 parent 68bf4b6 commit 29bea2a

File tree

8 files changed

+119
-19
lines changed

8 files changed

+119
-19
lines changed

docs/api/createEntityAdapter.mdx

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -377,6 +377,8 @@ If `updateMany()` is called with multiple updates targeted to the same ID, they
377377

378378
For both `updateOne()` and `updateMany()`, changing the ID of one existing entity to match the ID of a second existing entity will cause the first to replace the second completely.
379379

380+
Additionally, if there is no item for that ID, the update will be silently ignored.
381+
380382
## Examples
381383

382384
Exercising several of the CRUD methods and selectors:

docs/rtk-query/api/createApi.mdx

Lines changed: 26 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -153,6 +153,32 @@ Query endpoints (defined with `build.query()`) are used to cache data fetched fr
153153
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.
154154
155155
```ts title="Query endpoint definition" no-transpile
156+
export type FullTagDescription<TagType> = {
157+
type: TagType
158+
id?: number | string
159+
}
160+
export type TagDescription<TagType> = TagType | FullTagDescription<TagType>
161+
162+
type TagDescriptionArray<TagTypes extends string> = ReadonlyArray<
163+
TagDescription<TagTypes> | undefined | null
164+
>
165+
166+
export type ResultDescription<
167+
TagTypes extends string,
168+
ResultType,
169+
QueryArg,
170+
ErrorType,
171+
MetaType,
172+
> =
173+
| TagDescriptionArray<TagTypes>
174+
| (
175+
result: ResultType | undefined,
176+
error: ErrorType | undefined,
177+
arg: QueryArg,
178+
meta: MetaType,
179+
) => TagDescriptionArray<TagTypes>
180+
181+
156182
export type QueryDefinition<
157183
QueryArg,
158184
BaseQuery extends BaseQueryFn,

docs/rtk-query/usage/code-splitting.mdx

Lines changed: 66 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -10,11 +10,17 @@ description: 'RTK Query > Usage > Code Splitting: dynamic injection of endpoints
1010

1111
# Code Splitting
1212

13-
RTK Query makes it possible to trim down your initial bundle size by allowing you to inject additional endpoints after you've set up your initial service definition. This can be very beneficial for larger applications that may have _many_ endpoints.
13+
## Overview
1414

15-
`injectEndpoints` accepts a collection of endpoints, as well as an optional `overrideExisting` parameter.
15+
By default, an RTK Query API definition normally has all of the endpoint definitions in a single file. However, in larger applications this can result in very large files that may be harder to maintain. It also means that all of the relevant code is being imported right away.
1616

17-
Calling `injectEndpoints` will inject the endpoints into the original API, but also give you that same API with correct types for these endpoints back. (Unfortunately, it cannot modify the types for the original definition.)
17+
RTK Query allows dynamically injecting endpoint definitions into an existing API service object. This enables splitting up endpoints into multiple files for maintainability, as well as lazy-loading endpoint definitions and associated code to trim down initial bundle sizes. This can be very beneficial for larger applications that may have _many_ endpoints.
18+
19+
## Injecting Endpoints
20+
21+
`api.injectEndpoints` accepts a collection of endpoint definitions (same as `createApi`), as well as an optional `overrideExisting` parameter.
22+
23+
Calling `api.injectEndpoints` will inject the endpoints into the original API service object, modifying it immediately. It returns **the _same_ API service object reference**. If you're using TypeScript, the return value has the TS types for the new endpoints included. (Unfortunately, it cannot modify the types for the original API reference.)
1824

1925
A typical approach would be to have one empty central API slice definition:
2026

@@ -43,6 +49,7 @@ export const emptySplitApi = createApi({
4349
// file: extendedApi.ts
4450
import { emptySplitApi } from './emptySplitApi'
4551

52+
// NOTE: these are the _SAME_ API reference!
4653
const extendedApi = emptySplitApi.injectEndpoints({
4754
endpoints: (build) => ({
4855
example: build.query({
@@ -60,3 +67,59 @@ If you inject an endpoint that already exists and don't explicitly specify `over
6067
will not be overridden. In development mode, you will get a warning about this if `overrideExisting` is set to `false`,
6168
and an error will be throw if set to `'throw'`.
6269
:::
70+
71+
## Enhancing Endpoints
72+
73+
Sometimes you may also need to modify an existing API definition, such as adding additional tag types, or providing additional configuration options to a given endpoint.
74+
75+
`api.enhanceEndpoints` returns an updated and enhanced version of the API slice object, containing the combined endpoint definitions.
76+
77+
This is primarily useful for taking an API slice object that was code-generated from an API schema file like OpenAPI, and adding additional specific hand-written configuration for cache invalidation management on top of the generated endpoint definitions.
78+
79+
For example, `enhanceEndpoints` can be used to modify caching behavior by changing the values of `providesTags`, `invalidatesTags`, and `keepUnusedDataFor`:
80+
81+
```ts
82+
// file: api.ts noEmit
83+
import { createApi, fetchBaseQuery } from '@reduxjs/toolkit/query/react'
84+
85+
export const api = createApi({
86+
baseQuery: fetchBaseQuery({ baseUrl: '/' }),
87+
endpoints: (build) => ({
88+
getUserByUserId: build.query({
89+
query() {
90+
return ''
91+
},
92+
}),
93+
patchUserByUserId: build.mutation({
94+
query() {
95+
return ''
96+
},
97+
}),
98+
getUsers: build.query({
99+
query() {
100+
return ''
101+
},
102+
}),
103+
}),
104+
})
105+
106+
// file: enhanceEndpoints.ts
107+
import { api } from './api'
108+
109+
const enhancedApi = api.enhanceEndpoints({
110+
addTagTypes: ['User'],
111+
endpoints: {
112+
getUserByUserId: {
113+
providesTags: ['User'],
114+
},
115+
patchUserByUserId: {
116+
invalidatesTags: ['User'],
117+
},
118+
// alternatively, define a function which is called with the endpoint definition as an argument
119+
getUsers(endpoint) {
120+
endpoint.providesTags = ['User']
121+
endpoint.keepUnusedDataFor = 120
122+
},
123+
},
124+
})
125+
```

packages/toolkit/src/query/core/apiState.ts

Lines changed: 14 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -25,14 +25,6 @@ export type RefetchConfigOptions = {
2525
refetchOnFocus: boolean
2626
}
2727

28-
export type PageParamFunction<DataType, PageParam, QueryArg> = (
29-
firstPage: DataType,
30-
allPages: Array<DataType>,
31-
firstPageParam: PageParam,
32-
allPageParams: Array<PageParam>,
33-
queryArg: QueryArg,
34-
) => PageParam | undefined | null
35-
3628
export type InfiniteQueryConfigOptions<DataType, PageParam, QueryArg> = {
3729
/**
3830
* The initial page parameter to use for the first page fetch.
@@ -42,12 +34,24 @@ export type InfiniteQueryConfigOptions<DataType, PageParam, QueryArg> = {
4234
* This function is required to automatically get the next cursor for infinite queries.
4335
* The result will also be used to determine the value of `hasNextPage`.
4436
*/
45-
getNextPageParam: PageParamFunction<DataType, PageParam, QueryArg>
37+
getNextPageParam: (
38+
lastPage: DataType,
39+
allPages: Array<DataType>,
40+
lastPageParam: PageParam,
41+
allPageParams: Array<PageParam>,
42+
queryArg: QueryArg,
43+
) => PageParam | undefined | null
4644
/**
4745
* This function can be set to automatically get the previous cursor for infinite queries.
4846
* The result will also be used to determine the value of `hasPreviousPage`.
4947
*/
50-
getPreviousPageParam?: PageParamFunction<DataType, PageParam, QueryArg>
48+
getPreviousPageParam?: (
49+
firstPage: DataType,
50+
allPages: Array<DataType>,
51+
firstPageParam: PageParam,
52+
allPageParams: Array<PageParam>,
53+
queryArg: QueryArg,
54+
) => PageParam | undefined | null
5155
/**
5256
* If specified, only keep this many pages in cache at once.
5357
* If additional pages are fetched, older pages in the other

packages/toolkit/src/query/core/module.ts

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -471,13 +471,13 @@ export interface ApiEndpointMutation<
471471
export type ListenerActions = {
472472
/**
473473
* Will cause the RTK Query middleware to trigger any refetchOnReconnect-related behavior
474-
* @link https://rtk-query-docs.netlify.app/api/setupListeners
474+
* @link https://redux-toolkit.js.org/rtk-query/api/setupListeners
475475
*/
476476
onOnline: typeof onOnline
477477
onOffline: typeof onOffline
478478
/**
479479
* Will cause the RTK Query middleware to trigger any refetchOnFocus-related behavior
480-
* @link https://rtk-query-docs.netlify.app/api/setupListeners
480+
* @link https://redux-toolkit.js.org/rtk-query/api/setupListeners
481481
*/
482482
onFocus: typeof onFocus
483483
onFocusLost: typeof onFocusLost

packages/toolkit/src/query/createApi.ts

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -305,7 +305,7 @@ export type CreateApi<Modules extends ModuleName> = {
305305
/**
306306
* Creates a service to use in your application. Contains only the basic redux logic (the core module).
307307
*
308-
* @link https://rtk-query-docs.netlify.app/api/createApi
308+
* @link https://redux-toolkit.js.org/rtk-query/api/createApi
309309
*/
310310
<
311311
BaseQuery extends BaseQueryFn,
@@ -320,7 +320,7 @@ export type CreateApi<Modules extends ModuleName> = {
320320
/**
321321
* Builds a `createApi` method based on the provided `modules`.
322322
*
323-
* @link https://rtk-query-docs.netlify.app/concepts/customizing-create-api
323+
* @link https://redux-toolkit.js.org/rtk-query/usage/customizing-create-api
324324
*
325325
* @example
326326
* ```ts

packages/toolkit/src/query/endpointDefinitions.ts

Lines changed: 6 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -477,6 +477,10 @@ export enum DefinitionType {
477477
infinitequery = 'infinitequery',
478478
}
479479

480+
type TagDescriptionArray<TagTypes extends string> = ReadonlyArray<
481+
TagDescription<TagTypes> | undefined | null
482+
>
483+
480484
export type GetResultDescriptionFn<
481485
TagTypes extends string,
482486
ResultType,
@@ -488,7 +492,7 @@ export type GetResultDescriptionFn<
488492
error: ErrorType | undefined,
489493
arg: QueryArg,
490494
meta: MetaType,
491-
) => ReadonlyArray<TagDescription<TagTypes> | undefined | null>
495+
) => TagDescriptionArray<TagTypes>
492496

493497
export type FullTagDescription<TagType> = {
494498
type: TagType
@@ -506,7 +510,7 @@ export type ResultDescription<
506510
ErrorType,
507511
MetaType,
508512
> =
509-
| ReadonlyArray<TagDescription<TagTypes> | undefined | null>
513+
| TagDescriptionArray<TagTypes>
510514
| GetResultDescriptionFn<TagTypes, ResultType, QueryArg, ErrorType, MetaType>
511515

512516
type QueryTypes<

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

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1117,6 +1117,7 @@ export type UseInfiniteQueryStateOptions<
11171117
* `selectFromResult` allows you to get a specific segment from a query result in a performant manner.
11181118
* When using this feature, the component will not rerender unless the underlying data of the selected item has changed.
11191119
* If the selected item is one element in a larger collection, it will disregard changes to elements in the same collection.
1120+
* Note that this should always return an object (not a primitive), as RTKQ adds fields to the return value.
11201121
*
11211122
* @example
11221123
* ```ts

0 commit comments

Comments
 (0)