Skip to content

Commit 9f152eb

Browse files
authored
Pagination and cache invalidation
Add a section to specify that when we cache paginated queries, in case of deletion, we should delete not just the cache of that particular id, but the LIST as well to ensure that the total count is correct as well as to avoid the same record in adjacent pages.
1 parent 8a5d4bc commit 9f152eb

File tree

1 file changed

+27
-0
lines changed

1 file changed

+27
-0
lines changed

docs/rtk-query/usage/pagination.mdx

Lines changed: 27 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -76,6 +76,33 @@ const PostList = () => {
7676
};
7777
```
7878

79+
## Pagination and Caching
80+
81+
If you have caching enabled for your paginated queries, it maybe a good idea to invalidate the `LIST` cache as well when you do a `delete` mutation.
82+
83+
```ts title="src/features/services/post.ts
84+
// Or from '@reduxjs/toolkit/query' if not using the auto-generated hooks
85+
import { createApi, fetchBaseQuery } from '@reduxjs/toolkit/query/react'
86+
import { Post } from './types'
87+
88+
export const postApi = createApi({
89+
reducerPath: 'postsApi',
90+
baseQuery: fetchBaseQuery({ baseUrl: '/' }),
91+
tagTypes: ['Posts'],
92+
endpoints: (build) => ({
93+
deletePost: build.mutation<{ success: boolean; id: number }, number>({
94+
query(id) {
95+
return {
96+
url: `post/${id}`,
97+
method: 'DELETE',
98+
}
99+
},
100+
// Invalidates queries that subscribe to this Post `id` as well as the `LIST`.
101+
invalidatesTags: (result, error, id) => [{ type: 'Posts', id },
102+
{ type: 'Posts, 'LIST'}],
103+
}),
104+
})
105+
```
79106
## General Pagination Example
80107
81108
In the following example, you'll see `Loading` on the initial query, but then as you move forward we'll use the next/previous buttons as a _fetching_ indicator while any non-cached query is performed. When you go back, the cached data will be served instantaneously.

0 commit comments

Comments
 (0)