【问题标题】:Redux Toolkit Query: Reduce state from "mutation" responseRedux Toolkit 查询:从“突变”响应中减少状态
【发布时间】:2021-11-14 12:16:12
【问题描述】:

假设我有一个 RESTish API 来管理“帖子”。

  • 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 的内容更新该特定记录的减速器状态。

似乎是一个常见的用例,但我很难找到任何有关执行此类操作的文档。

【问题讨论】:

    标签: redux-toolkit rtk-query


    【解决方案1】:

    您可以稍后应用optimistic updates 中描述的机制:

    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)
              })
            )
          },
        }),
      }),
    })
    

    【讨论】:

    • 嗯,有道理。我认为onQueryStarted 让我失去了气味。谢谢!
    猜你喜欢
    • 2022-11-03
    • 1970-01-01
    • 2017-09-26
    • 2020-11-10
    • 2020-12-14
    • 2020-10-03
    • 2016-11-03
    • 2017-10-15
    • 2016-01-14
    相关资源
    最近更新 更多