Skip to content

Commit e90941d

Browse files
committed
📝 Expand on implementing manual cache updates
- Add `Manual Cache Updates` page - Replace `Optimistic Updates` sidebar link with `Manual Cache Updates` link, and move closer to top - Move `Optimistic Updates` content to a recipe within `Manual Cache Updates` - Delete old unused `cache-management` page (replaced by `cache-management-utils`, but old one was accidentally left behind)
1 parent 9e772d2 commit e90941d

File tree

8 files changed

+244
-182
lines changed

8 files changed

+244
-182
lines changed

docs/rtk-query/api/createApi.mdx

Lines changed: 4 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -452,15 +452,17 @@ Available to both [queries](../usage/queries.mdx) and [mutations](../usage/mutat
452452

453453
A function that is called when you start each individual query or mutation. The function is called with a lifecycle api object containing properties such as `queryFulfilled`, allowing code to be run when a query is started, when it succeeds, and when it fails (i.e. throughout the lifecycle of an individual query/mutation call).
454454

455-
Can be used in `mutations` for [optimistic updates](../usage/optimistic-updates.mdx).
455+
Can be used in `mutations` for [optimistic updates](../usage/manual-cache-updates.mdx#optimistic-updates).
456456

457457
#### Lifecycle API properties
458458

459459
- `dispatch` - The dispatch method for the store.
460460
- `getState` - A method to get the current state for the store.
461461
- `extra` - `extra` as provided as `thunk.extraArgument` to the `configureStore` `getDefaultMiddleware` option.
462462
- `requestId` - A unique ID generated for the query/mutation.
463-
- `queryFulfilled` - A Promise that will resolve with the (transformed) query result. If the query fails, this Promise will reject with the error. This allows you to `await` for the query to finish.
463+
- `queryFulfilled` - A Promise that will resolve with a `data` property (the transformed query result),
464+
and a `meta` property (`meta` returned by the `baseQuery`).
465+
If the query fails, this Promise will reject with the error. This allows you to `await` for the query to finish.
464466
- `getCacheEntry` - A function that gets the current value of the cache entry.
465467
- `updateCachedData` _(query endpoints only)_ - A function that accepts a 'recipe' callback specifying how to update the data for the corresponding cache at the time it is called. This uses `immer` internally, and updates can be written 'mutably' while safely producing the next immutable state.
466468

docs/rtk-query/api/created-api/cache-management-utils.mdx

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -9,7 +9,7 @@ hide_title: true
99

1010
# API Slices: Cache Management Utilities
1111

12-
The API slice object includes cache management utilities that are used for implementing [optimistic updates](../../usage/optimistic-updates.mdx). These are included in a `util` field inside the slice object.
12+
The API slice object includes cache management utilities that are used for implementing [optimistic updates](../../usage/manual-cache-updates.mdx#optimistic-updates). These are included in a `util` field inside the slice object.
1313

1414
### `updateQueryData`
1515

docs/rtk-query/api/created-api/cache-management.mdx

Lines changed: 0 additions & 87 deletions
This file was deleted.

docs/rtk-query/comparison.md

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -31,7 +31,7 @@ RTK Query has some unique API design aspects and capabilities that are worth con
3131
- Because RTK Query dispatches normal Redux actions as requests are processed, all actions are visible in the Redux DevTools. Additionally, every request is automatically visible to your Redux reducers and can easily update the global application state if necessary ([see example](https://github.com/reduxjs/redux-toolkit/issues/958#issuecomment-809570419)). You can use the endpoint [matcher functionality](./api/created-api/endpoints#matchers) to do additional processing of cache-related actions in your own reducers.
3232
- Like Redux itself, the main RTK Query functionality is UI-agnostic and can be used with any UI layer
3333
- You can easily invalidate entities or patch existing query data (via `util.updateQueryData`) from middleware.
34-
- RTK Query enables [streaming cache updates](./usage/streaming-updates.mdx), such as updating the initial fetched data as messages are received over a websocket, and has built in support for [optimistic updates](./usage/optimistic-updates.mdx) as well.
34+
- RTK Query enables [streaming cache updates](./usage/streaming-updates.mdx), such as updating the initial fetched data as messages are received over a websocket, and has built in support for [optimistic updates](./usage/manual-cache-updates.mdx#optimistic-updates) as well.
3535
- RTK Query ships a very tiny and flexible fetch wrapper: [`fetchBaseQuery`](./api/fetchBaseQuery.mdx). It's also very easy to [swap our client with your own](./usage/customizing-queries.mdx), such as using `axios`, `redaxios`, or something custom.
3636
- RTK Query has [a (currently experimental) code-gen tool](https://github.com/rtk-incubator/rtk-query-codegen) that will take an OpenAPI spec or GraphQL schema and give you a typed API client, as well as provide methods for enhancing the generated client after the fact.
3737

Lines changed: 236 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,236 @@
1+
---
2+
id: manual-cache-updates
3+
title: Manual Cache Updates
4+
sidebar_label: Manual Cache Updates
5+
hide_title: true
6+
description: 'RTK Query > Usage > Manual Cache Updates: Updating cached data manually'
7+
---
8+
9+
 
10+
11+
# Manual Cache Updates
12+
13+
## Overview
14+
15+
For most cases, in order to receive up to date data after a triggering a change in the backend,
16+
you can take advantage of `cache tag invalidation` to perform
17+
[automated re-fetching](./automated-refetching), which will cause a query to re-fetch it's data
18+
when it has been told that a mutation has occurred which would cause it's data to become out of date.
19+
In most cases, we recommend to use `automated re-fetching` as a preference over `manual cache updates`,
20+
unless you encounter the need to do so.
21+
22+
However, in some cases, you may want to update the cache manually. When you wish to update cache
23+
data that _already exists_ for query endpoints, you can do so using the
24+
[`updateQueryData`](../api/created-api/cache-management-utils.mdx#updatequerydata) thunk action
25+
available on the `util` object of your created API.
26+
27+
Anywhere you have access to the `dispatch` method for the store instance, you can dispatch the
28+
result of calling `updateQueryData` in order to update the cache data for a query endpoint,
29+
if the corresponding cache entry exists.
30+
31+
Use cases for manual cache updates include:
32+
33+
- Providing immediate feedback to the user when a mutation is attempted
34+
- After a mutation, updating a single item in a large list of items that is already cached,
35+
rather than re-fetching the whole list
36+
- Debouncing a large number of mutations with immediate feedback as though they are being
37+
applied, followed by a single request sent to the server to update the debounced attempts
38+
39+
## Recipes
40+
41+
### Optimistic Updates
42+
43+
When you wish to perform an update to cache data immediately after a [`mutation`](./mutations) is
44+
triggered, you can apply an `optimistic update`. This can be a useful pattern for when you want to
45+
give the user the impression that their changes are immediate, even while the mutation request is
46+
still in flight.
47+
48+
The core concepts for an optimistic update are:
49+
50+
- when you start a query or mutation, `onQueryStarted` will be executed
51+
- you manually update the cached data by dispatching `api.util.updateQueryData` within `onQueryStarted`
52+
- then, in the case that `queryFulfilled` rejects:
53+
- you roll it back via the `.undo` property of the object you got back from the earlier dispatch,
54+
OR
55+
- you invalidate the cache data via `api.util.invalidateTags` to trigger a full re-fetch of the data
56+
57+
:::tip
58+
Where many mutations are potentially triggered in short succession causing overlapping requests,
59+
you may encounter race conditions if attempting to roll back patches using the `.undo` property
60+
on failures. For these scenarios, it is often simplest and safest to invalidate the tags on error
61+
instead, and re-fetch truly up-to-date data straight from the server.
62+
:::
63+
64+
```ts title="Optimistic update mutation example (async await)"
65+
// file: types.ts noEmit
66+
export interface Post {
67+
id: number
68+
name: string
69+
}
70+
71+
// file: api.ts
72+
import { createApi, fetchBaseQuery } from '@reduxjs/toolkit/query'
73+
import { Post } from './types'
74+
75+
const api = createApi({
76+
baseQuery: fetchBaseQuery({
77+
baseUrl: '/',
78+
}),
79+
tagTypes: ['Post'],
80+
endpoints: (build) => ({
81+
getPost: build.query<Post, number>({
82+
query: (id) => `post/${id}`,
83+
providesTags: ['Post'],
84+
}),
85+
updatePost: build.mutation<void, Pick<Post, 'id'> & Partial<Post>>({
86+
query: ({ id, ...patch }) => ({
87+
url: `post/${id}`,
88+
method: 'PATCH',
89+
body: patch,
90+
}),
91+
invalidatesTags: ['Post'],
92+
// highlight-start
93+
async onQueryStarted({ id, ...patch }, { dispatch, queryFulfilled }) {
94+
const patchResult = dispatch(
95+
api.util.updateQueryData('getPost', id, (draft) => {
96+
Object.assign(draft, patch)
97+
})
98+
)
99+
try {
100+
await queryFulfilled
101+
} catch {
102+
patchResult.undo()
103+
104+
/**
105+
* Alternatively, on failure you can invalidate the corresponding cache tags
106+
* to trigger a re-fetch:
107+
* dispatch(api.util.invalidateTags(['Post']))
108+
*/
109+
}
110+
},
111+
// highlight-end
112+
}),
113+
}),
114+
})
115+
```
116+
117+
or, if you prefer the slightly shorter version with `.catch`
118+
119+
```diff
120+
- async onQueryStarted({ id, ...patch }, { dispatch, queryFulfilled }) {
121+
+ onQueryStarted({ id, ...patch }, { dispatch, queryFulfilled }) {
122+
const patchResult = dispatch(
123+
api.util.updateQueryData('getPost', id, (draft) => {
124+
Object.assign(draft, patch)
125+
})
126+
)
127+
- try {
128+
- await queryFulfilled
129+
- } catch {
130+
- patchResult.undo()
131+
- }
132+
+ queryFulfilled.catch(patchResult.undo)
133+
}
134+
```
135+
136+
#### Example
137+
138+
[React Optimistic Updates](./examples#react-optimistic-updates)
139+
140+
### Pessimistic Updates
141+
142+
When you wish to perform an update to cache data based on the response received from the server
143+
after a [`mutation`](./mutations) is triggered, you can apply a `pessimistic update`.
144+
The distinction between a `pessimistic update` and an `optimistic update` is that the
145+
`pessimistic update` will instead wait for the response from the server prior to updating
146+
the cached data.
147+
148+
The core concepts for a pessimistic update are:
149+
150+
- when you start a query or mutation, `onQueryStarted` will be executed
151+
- you await `queryFulfilled` to resolve to an object containing the transformed response from the
152+
server in the `data` property
153+
- you manually update the cached data by dispatching `api.util.updateQueryData` within
154+
`onQueryStarted`, using the data in the response from the server for your draft updates
155+
156+
```ts title="Pessimistic update mutation example (async await)"
157+
// file: types.ts noEmit
158+
export interface Post {
159+
id: number
160+
name: string
161+
}
162+
163+
// file: api.ts
164+
import { createApi, fetchBaseQuery } from '@reduxjs/toolkit/query'
165+
import { Post } from './types'
166+
167+
const api = createApi({
168+
baseQuery: fetchBaseQuery({
169+
baseUrl: '/',
170+
}),
171+
tagTypes: ['Post'],
172+
endpoints: (build) => ({
173+
getPost: build.query<Post, number>({
174+
query: (id) => `post/${id}`,
175+
providesTags: ['Post'],
176+
}),
177+
updatePost: build.mutation<Post, Pick<Post, 'id'> & Partial<Post>>({
178+
query: ({ id, ...patch }) => ({
179+
url: `post/${id}`,
180+
method: 'PATCH',
181+
body: patch,
182+
}),
183+
invalidatesTags: ['Post'],
184+
// highlight-start
185+
async onQueryStarted({ id, ...patch }, { dispatch, queryFulfilled }) {
186+
try {
187+
const { data: updatedPost } = await queryFulfilled
188+
const patchResult = dispatch(
189+
api.util.updateQueryData('getPost', id, (draft) => {
190+
Object.assign(draft, updatedPost)
191+
})
192+
)
193+
} catch {}
194+
},
195+
// highlight-end
196+
}),
197+
}),
198+
})
199+
```
200+
201+
### General Updates
202+
203+
If you find yourself wanting to update cache data elsewhere in your application, you can do so
204+
anywhere you have access to the `store.dispatch` method, including within React components via
205+
the [useDispatch](https://react-redux.js.org/api/hooks#usedispatch) hook (or a typed version such
206+
as [useAppDispatch](https://react-redux.js.org/using-react-redux/usage-with-typescript#define-typed-hooks)
207+
for typescript users).
208+
209+
:::info
210+
You should generally avoid manually updating the cache outside of the `onQueryStarted`
211+
callback for a mutation without a good reason, as RTK Query is intended to be used by considering
212+
your cached data as a reflection of the server-side state.
213+
:::
214+
215+
```tsx title="General manual cache update example"
216+
import { api } from './api'
217+
import { useAppDispatch } from './store/hooks'
218+
219+
function App() {
220+
const dispatch = useAppDispatch()
221+
222+
function handleClick() {
223+
/**
224+
* This will update the cache data for the query corresponding to the `getPosts` endpoint,
225+
* when that endpoint is used with no argument (undefined).
226+
*/
227+
const patchCollection = dispatch(
228+
api.util.updateQueryData('getPosts', undefined, (draftPosts) => {
229+
draftPosts.push({ id: 1, name: 'Teddy' })
230+
})
231+
)
232+
}
233+
234+
return <button onClick={handleClick}>Add post to cache</button>
235+
}
236+
```

docs/rtk-query/usage/mutations.mdx

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -79,7 +79,7 @@ const api = createApi({
7979

8080
:::info
8181

82-
The `onQueryStarted` method can be used for [optimistic updates](./optimistic-updates)
82+
The `onQueryStarted` method can be used for [optimistic updates](./manual-cache-updates.mdx#optimistic-updates)
8383

8484
:::
8585

0 commit comments

Comments
 (0)