Skip to content

Commit 8cd2545

Browse files
authored
Merge pull request #1074 from Shrugsy/docs/extend-detail-for-queries-and-endpoints
2 parents ea12adc + 4b629cb commit 8cd2545

File tree

12 files changed

+588
-260
lines changed

12 files changed

+588
-260
lines changed

docs/api/rtk-query/createApi.mdx

Lines changed: 336 additions & 147 deletions
Large diffs are not rendered by default.

docs/api/rtk-query/created-api/hooks.mdx

Lines changed: 13 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -267,11 +267,12 @@ type UseQueryResult<T> = {
267267
startedTimeStamp?: number // Timestamp for when the query was initiated
268268
fulfilledTimeStamp?: number // Timestamp for when the query was completed
269269

270-
isUninitialized: false // Query has not started yet.
271-
isLoading: false // Query is currently loading for the first time. No data yet.
272-
isFetching: false // Query is currently fetching, but might have data from an earlier request.
273-
isSuccess: false // Query has data from a successful load.
274-
isError: false // Query is currently in an "error" state.
270+
// Derived request status booleans
271+
isUninitialized: boolean // Query has not started yet.
272+
isLoading: boolean // Query is currently loading for the first time. No data yet.
273+
isFetching: boolean // Query is currently fetching, but might have data from an earlier request.
274+
isSuccess: boolean // Query has data from a successful load.
275+
isError: boolean // Query is currently in an "error" state.
275276

276277
refetch: () => void // A function to force refetch the query
277278
}
@@ -316,15 +317,18 @@ type UseMutationTrigger<T> = (
316317
}
317318

318319
type UseMutationResult<T> = {
320+
// Base query state
321+
originalArgs?: unknown // Arguments passed to the latest mutation call
319322
data?: T // Returned result if present
320-
endpointName?: string // The name of the given endpoint for the mutation
321323
error?: unknown // Error result if present
324+
endpointName?: string // The name of the given endpoint for the mutation
322325
fulfilledTimestamp?: number // Timestamp for when the mutation was completed
323-
isError: boolean // Mutation is currently in an "error" state
326+
327+
// Derived request status booleans
328+
isUninitialized: boolean // Mutation has not been fired yet
324329
isLoading: boolean // Mutation has been fired and is awaiting a response
325330
isSuccess: boolean // Mutation has data from a successful call
326-
isUninitialized: boolean // Mutation has not been fired yet
327-
originalArgs?: unknown // Arguments passed to the latest mutation call
331+
isError: boolean // Mutation is currently in an "error" state
328332
startedTimeStamp?: number // Timestamp for when the latest mutation was initiated
329333
}
330334
```

docs/usage/rtk-query/cached-data.mdx

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -15,7 +15,7 @@ RTK Query provides a number of concepts and tools to manipulate the cache behavi
1515

1616
### Tags
1717

18-
_see also: [tagTypes](../../api/rtk-query/createApi#tagtypes)_
18+
_see also: [tagTypes API reference](../../api/rtk-query/createApi.mdx#tagtypes)_
1919

2020
For RTK Query, _tags_ are just a name that you can give to a specific collection of data to control caching and invalidation behavior for refetching purposes. It can be considered as a 'label' attached to cached data that is read after a `mutation`, to decide whether the data should be affected by the mutation.
2121

@@ -25,15 +25,15 @@ An individual `tag` has a `type`, represented as a `string` name, and an optiona
2525

2626
### Providing tags
2727

28-
_see also: [Anatomy of an endpoint](../../api/rtk-query/createApi#anatomy-of-an-endpoint)_
28+
_see also: [providesTags API reference](../../api/rtk-query/createApi.mdx#providestags)_
2929

3030
A _query_ can have it's cached data _provide_ tags. Doing so determines which 'tag' is attached to the cached data returned by the query.
3131

3232
The `providesTags` argument can either be an array of `string` (such as `['Post']`), `{type: string, id?: string|number}` (such as `[{type: 'Post', id: 1}]`), or a callback that returns such an array. That function will be passed the result as the first argument, the response error as the second argument, and the argument originally passed into the `query` method as the third argument. Note that either the result or error arguments may be undefined based on whether the query was successful or not.
3333

3434
### Invalidating tags
3535

36-
_see also: [Anatomy of an endpoint](../../api/rtk-query/createApi#anatomy-of-an-endpoint)_
36+
_see also: [invalidatesTags API reference](../../api/rtk-query/createApi.mdx#invalidatesTags)_
3737

3838
A _mutation_ can _invalidate_ specific cached data based on the tags. Doing so determines which cached data will be either refetched or removed from the cache.
3939

docs/usage/rtk-query/conditional-fetching.mdx

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -13,6 +13,10 @@ If you want to prevent a query from automatically running, you can use the `skip
1313

1414
[remarks](docblock://query/react/buildHooks.ts?token=UseQuerySubscriptionOptions.skip)
1515

16+
:::tip
17+
Typescript users may wish to use [`skipToken`](../../api/rtk-query/created-api/hooks.mdx#skiptoken) as an alternative to the `skip` option in order to skip running a query, while still keeping types for the endpoint accurate.
18+
:::
19+
1620
### Example
1721

1822
<iframe

docs/usage/rtk-query/customizing-queries.mdx

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -286,7 +286,7 @@ export const { useGetPostsQuery, useGetPostQuery } = api
286286

287287
### Excluding baseQuery with queryFn
288288

289-
Individual endpoints on [`createApi`](../../api/rtk-query/createApi) accept a [`queryFn`](../../api/rtk-query/createApi#anatomy-of-an-endpoint) property which allows a given endpoint to ignore `baseQuery` for that endpoint by providing an inline function determining how that query resolves.
289+
Individual endpoints on [`createApi`](../../api/rtk-query/createApi) accept a [`queryFn`](../../api/rtk-query/createApi#queryfn) property which allows a given endpoint to ignore `baseQuery` for that endpoint by providing an inline function determining how that query resolves.
290290

291291
This can be useful for scenarios where you want to have particularly different behaviour for a single endpoint, or where the query itself is not relevant. Such situations may include:
292292

docs/usage/rtk-query/mutations.mdx

Lines changed: 32 additions & 42 deletions
Original file line numberDiff line numberDiff line change
@@ -11,6 +11,8 @@ Unlike `useQuery`, `useMutation` returns a tuple. The first item in the tuple is
1111

1212
Unlike the `useQuery` hook, the `useMutation` hook doesn't execute automatically. To run a mutation you have to call the trigger function returned as the first tuple value from the hook.
1313

14+
See [`useMutation`](../../api/rtk-query/created-api/hooks.mdx#usemutation) for the hook signature and additional details.
15+
1416
```ts title="Example of all mutation endpoint options"
1517
// file: types.ts noEmit
1618
export interface Post {
@@ -68,47 +70,32 @@ const api = createApi({
6870
Notice the `onQueryStarted` method? Be sure to check out how it can be used for [optimistic updates](./optimistic-updates)
6971
:::
7072

71-
### Type interfaces
72-
73-
```ts title="Mutation endpoint definition" no-transpile
74-
export type MutationDefinition<
75-
QueryArg,
76-
BaseQuery extends BaseQueryFn,
77-
TagTypes extends string,
78-
ResultType,
79-
ReducerPath extends string = string,
80-
Context = Record<string, any>
81-
> = BaseEndpointDefinition<QueryArg, BaseQuery, ResultType> & {
82-
type: DefinitionType.mutation
83-
invalidatesTags?: ResultDescription<TagTypes, ResultType, QueryArg>
84-
providesTags?: never
85-
onQueryStarted?(
86-
arg: QueryArg,
87-
{
88-
dispatch,
89-
getState,
90-
queryFulfilled,
91-
requestId,
92-
extra,
93-
getCacheEntry,
94-
}: MutationLifecycleApi
95-
): Promise<void>
96-
onCacheEntryAdded?(
97-
arg: QueryArg,
98-
{
99-
dispatch,
100-
getState,
101-
extra,
102-
requestId,
103-
cacheEntryRemoved,
104-
cacheDataLoaded,
105-
getCacheEntry,
106-
}: MutationCacheLifecycleApi
107-
): Promise<void>
108-
}
109-
```
73+
### Performing Mutations with React Hooks
74+
75+
#### Frequently Used Mutation Hook Return Values
76+
77+
The `useMutation` hook returns a tuple containing a `mutation trigger` function, as well as an object containing properties about the `mutation result`.
78+
79+
The `mutation trigger` is a function that when called, will fire off the mutation request for that endpoint. Calling the `mutation trigger` returns a promise with an `unwrap` property, which can be called to unwrap the mutation call and provide the raw response/error. This can be useful if you wish to determine whether the mutation succeeds/fails inline at the call-site.
80+
81+
The `mutation result` is an object containing properties such as the latest `data` for the mutation request, as well as status booleans for the current request lifecycle state.
82+
83+
Below are some of the most frequently used properties on the `mutation result` object. Refer to [`useMutation`](../../api/rtk-query/created-api/hooks.mdx#usemutation) for an extensive list of all returned properties.
84+
85+
- `data` - The returned result if present.
86+
- `error` - The error result if present.
87+
- `isUninitialized` - When true, indicates that the mutation has not been fired yet.
88+
- `isLoading` - When true, indicates that the mutation has been fired and is awaiting a response.
89+
- `isSuccess` - When true, indicates that the last mutation fired has data from a successful request.
90+
- `isError` - When true, indicates that the last mutation fired resulted in an error state.
91+
92+
:::note
93+
94+
With RTK Query, a mutation does contain a semantic distinction between 'loading' and 'fetching' in the way that a [query does](./queries.mdx#frequently-used-query-hook-return-values). For a mutation, subsequent calls are not assumed to be necessarily related, so a mutation is either 'loading' or 'not loading', with no concept of 're-fetching'.
95+
96+
:::
11097

111-
### Basic Mutation
98+
#### Example
11299

113100
This is a modified version of the complete example you can see at the bottom of the page to highlight the `updatePost` mutation. In this scenario, a post is fetched with `useQuery`, and then a `EditablePostName` component is rendered that allows us to edit the name of the post.
114101

@@ -118,11 +105,12 @@ export const PostDetail = () => {
118105

119106
const { data: post } = useGetPostQuery(id)
120107

108+
// highlight-start
121109
const [
122-
// highlight-next-line
123110
updatePost, // This is the mutation trigger
124-
{ isLoading: isUpdating }, // You can use the `isLoading` flag, or do custom logic with `status`
111+
{ isLoading: isUpdating }, // This is the destructured mutation result
125112
] = useUpdatePostMutation()
113+
// highlight-end
126114

127115
return (
128116
<Box p={4}>
@@ -140,7 +128,9 @@ export const PostDetail = () => {
140128
// highlight-end
141129
)
142130
}}
131+
// highlight-start
143132
isLoading={isUpdating}
133+
// highlight-end
144134
/>
145135
</Box>
146136
)

docs/usage/rtk-query/queries.mdx

Lines changed: 33 additions & 37 deletions
Original file line numberDiff line numberDiff line change
@@ -13,6 +13,8 @@ By default, RTK Query ships with [`fetchBaseQuery`](../../api/rtk-query/fetchBas
1313

1414
> Depending on your environment, you may need to polyfill `fetch` with `node-fetch` or `cross-fetch` if you choose to use `fetchBaseQuery` or `fetch` on its own.
1515
16+
See [`useQuery`](../../api/rtk-query/created-api/hooks.mdx#usequery) for the hook signature and additional details.
17+
1618
```ts title="Example of all query endpoint options"
1719
// file: types.ts noEmit
1820
export interface Post {
@@ -71,7 +73,7 @@ const api = createApi({
7173
})
7274
```
7375

74-
### Performing queries with React Hooks
76+
### Performing Queries with React Hooks
7577

7678
If you're using React Hooks, RTK Query does a few additional things for you. The primary benefit is that you get a render-optimized hook that allows you to have 'background fetching' as well as [derived booleans](#query-hook-return-types) for convenience.
7779

@@ -81,48 +83,42 @@ Hooks are automatically generated based on the name of the `endpoint` in the ser
8183

8284
There are 5 query-related hooks:
8385

84-
1. [`useQuery`](../../api/rtk-query/created-api/hooks/#usequery)
85-
- Composes `useQuerySubscription` and `useQueryState` and is the primary hook
86-
2. [`useQuerySubscription`](../../api/rtk-query/created-api/hooks/#usequerysubscription)
87-
- Returns a `refetch` function and accepts all hook options
88-
3. [`useQueryState`](../../api/rtk-query/created-api/hooks/#usequerystate)
89-
- Returns the query state and accepts `skip` and `selectFromResult`
90-
4. [`useLazyQuery`](../../api/rtk-query/created-api/hooks/#uselazyquery)
91-
- Returns a tuple with a `fetch` function, the query result, and last promise info
92-
5. [`useLazyQuerySubscription`](../../api/rtk-query/created-api/hooks/#uselazyquerysubscription)
93-
- Returns a tuple with a `fetch` function, and last promise info
86+
1. [`useQuery`](../../api/rtk-query/created-api/hooks.mdx#usequery)
87+
- Composes `useQuerySubscription` and `useQueryState` and is the primary hook. Automatically triggers fetches of data from an endpoint, 'subscribes' the component to the cached data, and reads the request status and cached data from the Redux store.
88+
2. [`useQuerySubscription`](../../api/rtk-query/created-api/hooks.mdx#usequerysubscription)
89+
- Returns a `refetch` function and accepts all hook options. Automatically triggers fetches of data from an endpoint, and 'subscribes' the component to the cached data.
90+
3. [`useQueryState`](../../api/rtk-query/created-api/hooks.mdx#usequerystate)
91+
- Returns the query state and accepts `skip` and `selectFromResult`. Reads the request status and cached data from the Redux store.
92+
4. [`useLazyQuery`](../../api/rtk-query/created-api/hooks.mdx#uselazyquery)
93+
- Returns a tuple with a `fetch` function, the query result, and last promise info. Similar to `useQuery`, but with manual control over when the data fetching occurs.
94+
5. [`useLazyQuerySubscription`](../../api/rtk-query/created-api/hooks.mdx#uselazyquerysubscription)
95+
- Returns a tuple with a `fetch` function, and last promise info. Similar to `useQuerySubscription`, but with manual control over when the data fetching occurs.
9496

9597
#### Query Hook Options
9698

97-
- [skip](./conditional-fetching) - Defaults to `false`
98-
- [pollingInterval](./polling) - Defaults to `0` _(off)_
99-
- [selectFromResult](#selecting-data-from-a-query-result) - Optional, allows you to return a subset of a query
100-
- [refetchOnMountOrArgChange](../../api/rtk-query/createApi#refetchonmountorargchange) - Defaults to `false`
101-
- [refetchOnFocus](../../api/rtk-query/createApi#refetchonfocus) - Defaults to `false`
102-
- [refetchOnReconnect](../../api/rtk-query/createApi#refetchonreconnect) - Defaults to `false`
99+
- [skip](./conditional-fetching) - Allows a query to 'skip' running for that render. Defaults to `false`
100+
- [pollingInterval](./polling) - Allows a query to automatically refetch on a provided interval, specified in milliseconds. Defaults to `0` _(off)_
101+
- [selectFromResult](#selecting-data-from-a-query-result) - Allows altering the returned value of the hook to obtain a subset of the result, render-optimized for the returned subset.
102+
- [refetchOnMountOrArgChange](../../api/rtk-query/createApi#refetchonmountorargchange) - Allows forcing the query to always refetch on mount (when `true` is provided). Allows forcing the query to refetch if enough time (in seconds) has passed since the last query for the same cache (when a `number` is provided). Defaults to `false`
103+
- [refetchOnFocus](../../api/rtk-query/createApi#refetchonfocus) - Allows forcing the query to refetch when the browser window regains focus. Defaults to `false`
104+
- [refetchOnReconnect](../../api/rtk-query/createApi#refetchonreconnect) - Allows forcing the query to refetch when regaining a network connection. Defaults to `false`
103105

104106
> All `refetch`-related options will override the defaults you may have set in [createApi](../../api/rtk-query/createApi)
105107
106-
#### Query Hook Return Types
107-
108-
```ts title="All returned elements" no-transpile
109-
// Base query state
110-
originalArgs?: unknown; // Arguments passed to the query
111-
data?: unknown; // Returned result if present
112-
error?: unknown; // Error result if present
113-
requestId?: string; // A string generated by RTK Query
114-
endpointName?: string; // The name of the given endpoint for the query
115-
startedTimeStamp?: number; // Timestamp for when the query was initiated
116-
fulfilledTimeStamp?: number; // Timestamp for when the query was completed
117-
118-
isUninitialized: false; // Query has not started yet.
119-
isLoading: false; // Query is currently loading for the first time. No data yet.
120-
isFetching: false; // Query is currently fetching, but might have data from an earlier request.
121-
isSuccess: false; // Query has data from a successful load.
122-
isError: false; // Query is currently in "error" state.
123-
124-
refetch: () => void; // A function to force refetch the query
125-
```
108+
#### Frequently Used Query Hook Return Values
109+
110+
The query hook returns an object containing properties such as the latest `data` for the query request, as well as status booleans for the current request lifecycle state. Below are some of the most frequently used properties. Refer to [`useQuery`](../../api/rtk-query/created-api/hooks.mdx#usequery) for an extensive list of all returned properties.
111+
112+
- `data` - The returned result if present.
113+
- `error` - The error result if present.
114+
- `isUninitialized` - When true, indicates that the query has not started yet.
115+
- `isLoading` - When true, indicates that the query is currently loading for the first time, and has no data yet. This will be `true` for the first request fired off, but _not_ for subsequent requests.
116+
- `isFetching` - When true, indicates that the query is currently fetching, but might have data from an earlier request. This will be `true` for both the first request fired off, as well as subsequent requests.
117+
- `isSuccess` - When true, indicates that the query has data from a successful request.
118+
- `isError` - When true, indicates that the query is in an `error` state.
119+
- `refetch` - A function to force refetch the query
120+
121+
#### Example
126122

127123
Here is an example of a `PostDetail` component:
128124

docs/usage/rtk-query/streaming-updates.mdx

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -11,7 +11,7 @@ RTK Query gives you the ability to receive **streaming updates** for persistent
1111

1212
Streaming updates can be used to enable the API to receive real-time updates to the back-end data, such as new entries being created, or important properties being updated.
1313

14-
To enable streaming updates for a query, pass the asynchronous `onCacheEntryAdded` function to the query, including the logic for how to update the query when streamed data is received. See [anatomy of an endpoint](../../api/rtk-query/createApi#anatomy-of-an-endpoint) for more details.
14+
To enable streaming updates for a query, pass the asynchronous `onCacheEntryAdded` function to the query, including the logic for how to update the query when streamed data is received. See [`onCacheEntryAdded` API reference](../../api/rtk-query/createApi#onCacheEntryAdded) for more details.
1515

1616
## When to use streaming updates
1717

src/query/core/buildMiddleware/cacheLifecycle.ts

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -36,7 +36,7 @@ declare module '../../endpointDefinitions' {
3636
>
3737
/**
3838
* Updates the current cache entry value.
39-
* For documentation see `api.util.updateQueryData.
39+
* For documentation see `api.util.updateQueryData`.
4040
*/
4141
updateCachedData(updateRecipe: Recipe<ResultType>): PatchCollection
4242
}

src/query/createApi.ts

Lines changed: 23 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -98,6 +98,29 @@ export interface CreateApiOptions<
9898
): Definitions
9999
/**
100100
* Defaults to `60` _(this value is in seconds)_. This is how long RTK Query will keep your data cached for **after** the last component unsubscribes. For example, if you query an endpoint, then unmount the component, then mount another component that makes the same request within the given time frame, the most recent value will be served from the cache.
101+
*
102+
* ```ts
103+
* // codeblock-meta title="keepUnusedDataFor example"
104+
*
105+
* import { createApi, fetchBaseQuery } from '@reduxjs/toolkit/query/react'
106+
* interface Post {
107+
* id: number
108+
* name: string
109+
* }
110+
* type PostsResponse = Post[]
111+
*
112+
* const api = createApi({
113+
* baseQuery: fetchBaseQuery({ baseUrl: '/' }),
114+
* endpoints: (build) => ({
115+
* getPosts: build.query<PostsResponse, void>({
116+
* query: () => 'posts',
117+
* // highlight-start
118+
* keepUnusedDataFor: 5
119+
* // highlight-end
120+
* })
121+
* })
122+
* })
123+
* ```
101124
*/
102125
keepUnusedDataFor?: number
103126
/**

0 commit comments

Comments
 (0)