在 redux 教程中,我们学习了如何执行乐观更新:
第 8 部分-rtk-query-advanced#implementing-optimistic-updates https://redux.js.org/tutorials/essentials/part-8-rtk-query-advanced#implementing-optimistic-updates
但在 API 参考中更新查询数据 https://redux-toolkit.js.org/rtk-query/api/created-api/cache-management-utils#updatequerydata,我发现一个args
必须传入:
const updateQueryData = (
endpointName: string,
args: any,
updateRecipe: (draft: Draft<CachedState>) => void
) => ThunkAction<PatchCollection, PartialState, any, AnyAction>;
所以,如果我们的帖子有分页,
getPosts: builder.query({
query: (current: number) => `/posts?current=${current}`,
providesTags: ['Post']
}),
这个时候我们如何进行乐观更新呢?
// Is there a way to update all getPosts caches?
// Am I missing some documents?
apiSlice.util.updateQueryData('getPosts', ???, (draft) => {
const post = draft.find((post) => post.id === postId)
if (post) {
post.reactions[reaction]++
}
})