Skip to content

Commit

Permalink
Merge pull request #1525 from Shrugsy/docs/expand-on-manual-cache-upd…
Browse files Browse the repository at this point in the history
…ates
  • Loading branch information
markerikson authored Oct 1, 2021
2 parents 02808ab + 2670c15 commit 97319a3
Show file tree
Hide file tree
Showing 9 changed files with 258 additions and 186 deletions.
6 changes: 4 additions & 2 deletions docs/rtk-query/api/createApi.mdx
Original file line number Diff line number Diff line change
Expand Up @@ -452,15 +452,17 @@ Available to both [queries](../usage/queries.mdx) and [mutations](../usage/mutat

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).

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

#### Lifecycle API properties

- `dispatch` - The dispatch method for the store.
- `getState` - A method to get the current state for the store.
- `extra` - `extra` as provided as `thunk.extraArgument` to the `configureStore` `getDefaultMiddleware` option.
- `requestId` - A unique ID generated for the query/mutation.
- `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.
- `queryFulfilled` - A Promise that will resolve with a `data` property (the transformed query result),
and a `meta` property (`meta` returned by the `baseQuery`).
If the query fails, this Promise will reject with the error. This allows you to `await` for the query to finish.
- `getCacheEntry` - A function that gets the current value of the cache entry.
- `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.

Expand Down
2 changes: 1 addition & 1 deletion docs/rtk-query/api/created-api/cache-management-utils.mdx
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,7 @@ hide_title: true

# API Slices: Cache Management Utilities

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.
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.

### `updateQueryData`

Expand Down
87 changes: 0 additions & 87 deletions docs/rtk-query/api/created-api/cache-management.mdx

This file was deleted.

2 changes: 1 addition & 1 deletion docs/rtk-query/comparison.md
Original file line number Diff line number Diff line change
Expand Up @@ -31,7 +31,7 @@ RTK Query has some unique API design aspects and capabilities that are worth con
- 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.
- Like Redux itself, the main RTK Query functionality is UI-agnostic and can be used with any UI layer
- You can easily invalidate entities or patch existing query data (via `util.updateQueryData`) from middleware.
- 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.
- 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.
- 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.
- 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.

Expand Down
243 changes: 243 additions & 0 deletions docs/rtk-query/usage/manual-cache-updates.mdx
Original file line number Diff line number Diff line change
@@ -0,0 +1,243 @@
---
id: manual-cache-updates
title: Manual Cache Updates
sidebar_label: Manual Cache Updates
hide_title: true
description: 'RTK Query > Usage > Manual Cache Updates: Updating cached data manually'
---

 

# Manual Cache Updates

## Overview

For most cases, in order to receive up to date data after a triggering a change in the backend,
you can take advantage of `cache tag invalidation` to perform
[automated re-fetching](./automated-refetching), which will cause a query to re-fetch it's data
when it has been told that a mutation has occurred which would cause it's data to become out of date.
In most cases, we recommend to use `automated re-fetching` as a preference over `manual cache updates`,
unless you encounter the need to do so.

However, in some cases, you may want to update the cache manually. When you wish to update cache
data that _already exists_ for query endpoints, you can do so using the
[`updateQueryData`](../api/created-api/cache-management-utils.mdx#updatequerydata) thunk action
available on the `util` object of your created API.

Anywhere you have access to the `dispatch` method for the store instance, you can dispatch the
result of calling `updateQueryData` in order to update the cache data for a query endpoint,
if the corresponding cache entry exists.

Use cases for manual cache updates include:

- Providing immediate feedback to the user when a mutation is attempted
- After a mutation, updating a single item in a large list of items that is already cached,
rather than re-fetching the whole list
- Debouncing a large number of mutations with immediate feedback as though they are being
applied, followed by a single request sent to the server to update the debounced attempts

:::note
`updateQueryData` is strictly intended to perform _updates_ to existing cache entries,
not create new entries. If an `updateQueryData` thunk action is dispatched that corresponds to
no existing cache entry for the provided `endpointName` + `args` combination, the provided `recipe`
will not be called, and no `patches` or `inversePatches` will be returned.
:::

## Recipes

### Optimistic Updates

When you wish to perform an update to cache data immediately after a [`mutation`](./mutations) is
triggered, you can apply an `optimistic update`. This can be a useful pattern for when you want to
give the user the impression that their changes are immediate, even while the mutation request is
still in flight.

The core concepts for an optimistic update are:

- when you start a query or mutation, `onQueryStarted` will be executed
- you manually update the cached data by dispatching `api.util.updateQueryData` within `onQueryStarted`
- then, in the case that `queryFulfilled` rejects:
- you roll it back via the `.undo` property of the object you got back from the earlier dispatch,
OR
- you invalidate the cache data via `api.util.invalidateTags` to trigger a full re-fetch of the data

:::tip
Where many mutations are potentially triggered in short succession causing overlapping requests,
you may encounter race conditions if attempting to roll back patches using the `.undo` property
on failures. For these scenarios, it is often simplest and safest to invalidate the tags on error
instead, and re-fetch truly up-to-date data from the server.
:::

```ts title="Optimistic update mutation example (async await)"
// file: types.ts noEmit
export interface Post {
id: number
name: string
}

// file: api.ts
import { createApi, fetchBaseQuery } from '@reduxjs/toolkit/query'
import { Post } from './types'

const api = createApi({
baseQuery: fetchBaseQuery({
baseUrl: '/',
}),
tagTypes: ['Post'],
endpoints: (build) => ({
getPost: build.query<Post, number>({
query: (id) => `post/${id}`,
providesTags: ['Post'],
}),
updatePost: build.mutation<void, Pick<Post, 'id'> & Partial<Post>>({
query: ({ id, ...patch }) => ({
url: `post/${id}`,
method: 'PATCH',
body: patch,
}),
invalidatesTags: ['Post'],
// highlight-start
async onQueryStarted({ id, ...patch }, { dispatch, queryFulfilled }) {
const patchResult = dispatch(
api.util.updateQueryData('getPost', id, (draft) => {
Object.assign(draft, patch)
})
)
try {
await queryFulfilled
} catch {
patchResult.undo()

/**
* Alternatively, on failure you can invalidate the corresponding cache tags
* to trigger a re-fetch:
* dispatch(api.util.invalidateTags(['Post']))
*/
}
},
// highlight-end
}),
}),
})
```

or, if you prefer the slightly shorter version with `.catch`

```diff
- async onQueryStarted({ id, ...patch }, { dispatch, queryFulfilled }) {
+ onQueryStarted({ id, ...patch }, { dispatch, queryFulfilled }) {
const patchResult = dispatch(
api.util.updateQueryData('getPost', id, (draft) => {
Object.assign(draft, patch)
})
)
- try {
- await queryFulfilled
- } catch {
- patchResult.undo()
- }
+ queryFulfilled.catch(patchResult.undo)
}
```

#### Example

[React Optimistic Updates](./examples#react-optimistic-updates)

### Pessimistic Updates

When you wish to perform an update to cache data based on the response received from the server
after a [`mutation`](./mutations) is triggered, you can apply a `pessimistic update`.
The distinction between a `pessimistic update` and an `optimistic update` is that the
`pessimistic update` will instead wait for the response from the server prior to updating
the cached data.

The core concepts for a pessimistic update are:

- when you start a query or mutation, `onQueryStarted` will be executed
- you await `queryFulfilled` to resolve to an object containing the transformed response from the
server in the `data` property
- you manually update the cached data by dispatching `api.util.updateQueryData` within
`onQueryStarted`, using the data in the response from the server for your draft updates

```ts title="Pessimistic update mutation example (async await)"
// file: types.ts noEmit
export interface Post {
id: number
name: string
}

// file: api.ts
import { createApi, fetchBaseQuery } from '@reduxjs/toolkit/query'
import { Post } from './types'

const api = createApi({
baseQuery: fetchBaseQuery({
baseUrl: '/',
}),
tagTypes: ['Post'],
endpoints: (build) => ({
getPost: build.query<Post, number>({
query: (id) => `post/${id}`,
providesTags: ['Post'],
}),
updatePost: build.mutation<Post, Pick<Post, 'id'> & Partial<Post>>({
query: ({ id, ...patch }) => ({
url: `post/${id}`,
method: 'PATCH',
body: patch,
}),
invalidatesTags: ['Post'],
// highlight-start
async onQueryStarted({ id, ...patch }, { dispatch, queryFulfilled }) {
try {
const { data: updatedPost } = await queryFulfilled
const patchResult = dispatch(
api.util.updateQueryData('getPost', id, (draft) => {
Object.assign(draft, updatedPost)
})
)
} catch {}
},
// highlight-end
}),
}),
})
```

### General Updates

If you find yourself wanting to update cache data elsewhere in your application, you can do so
anywhere you have access to the `store.dispatch` method, including within React components via
the [useDispatch](https://react-redux.js.org/api/hooks#usedispatch) hook (or a typed version such
as [useAppDispatch](https://react-redux.js.org/using-react-redux/usage-with-typescript#define-typed-hooks)
for typescript users).

:::info
You should generally avoid manually updating the cache outside of the `onQueryStarted`
callback for a mutation without a good reason, as RTK Query is intended to be used by considering
your cached data as a reflection of the server-side state.
:::

```tsx title="General manual cache update example"
import { api } from './api'
import { useAppDispatch } from './store/hooks'

function App() {
const dispatch = useAppDispatch()

function handleClick() {
/**
* This will update the cache data for the query corresponding to the `getPosts` endpoint,
* when that endpoint is used with no argument (undefined).
*/
const patchCollection = dispatch(
api.util.updateQueryData('getPosts', undefined, (draftPosts) => {
draftPosts.push({ id: 1, name: 'Teddy' })
})
)
}

return <button onClick={handleClick}>Add post to cache</button>
}
```
2 changes: 1 addition & 1 deletion docs/rtk-query/usage/mutations.mdx
Original file line number Diff line number Diff line change
Expand Up @@ -79,7 +79,7 @@ const api = createApi({

:::info

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

:::

Expand Down
Loading

0 comments on commit 97319a3

Please sign in to comment.