假设我有一个rest API来管理"post "
GET /posts
返回所有帖子PATCH /posts:id
更新一篇文章并回复新的记录数据
我可以通过以下方式使用RTK查询来实现:
const TAG_TYPE = 'POST';
// Define a service using a base URL and expected endpoints
export const postsApi = createApi({
reducerPath: 'postsApi',
tagTypes: [TAG_TYPE],
baseQuery,
endpoints: (builder) => ({
getPosts: builder.query<Form[], string>({
query: () => `/posts`,
providesTags: (result) =>
[
{ type: TAG_TYPE, id: 'LIST' },
],
}),
updatePost: builder.mutation<any, { formId: string; formData: any }>({
// note: an optional `queryFn` may be used in place of `query`
query: (data) => ({
url: `/post/${data.formId}`,
method: 'PATCH',
body: data.formData,
}),
// this causes a full re-query.
// Would be more efficient to update state based on resp.body
invalidatesTags: [{ type: TAG_TYPE, id: 'LIST' }],
}),
}),
});
当updatePost
运行时,它使LIST
标签无效,导致getPosts
再次运行。
然而,由于PATCH
操作响应新的数据本身,我想避免做一个额外的服务器请求,而只是更新我的减速机状态为特定的记录与response.body
的内容。
似乎是一个常见的用例,但我正在努力找到任何关于这样做的文档。
您可以稍后应用乐观更新中描述的机制:
import { createApi, fetchBaseQuery } from '@reduxjs/toolkit/query'
import { Post } from './types'
const api = createApi({
// ...
endpoints: (build) => ({
// ...
updatePost: build.mutation<void, Pick<Post, 'id'> & Partial<Post>>({
query: ({ id, ...patch }) => ({
// ...
}),
async onQueryStarted({ id, ...patch }, { dispatch, queryFulfilled }) {
const { data } = await queryFulfilled
dispatch(
api.util.updateQueryData('getPost', id, (draft) => {
Object.assign(draft, data)
})
)
},
}),
}),
})