【问题标题】:How to save the results of a mutation in Redux toolkit createAPI for later usage?如何在 Redux 工具包 createAPI 中保存突变结果以备后用?
【发布时间】:2022-11-18 14:41:46
【问题描述】:

我最近开始使用 RTK 查询在我的应用程序中获取数据。在一个用例中,我想使用 createAPI 突变的结果,我已经在服务器上创建了一次资源。这涉及创建特定的有效负载。

import { createApi, fetchBaseQuery } from '@reduxjs/toolkit/query/react';

export const createResource = createApi({
  reducerPath: 'someReducerPath',
  baseQuery: fetchBaseQuery({ baseUrl: window.API_URL }),
  endpoints: (builder) => ({
    postResource: builder.query({
      // postBody in the parameter is received from the caller function.
      //It is an object containing the payload
      query: (postBody) => ({
        url: 'someURL',
        method: 'POST',
        body: postBody
      }),
      transformResponse: (response) => response
    }),
  }),
});

// Export hooks for usage in functional components, which are
// auto-generated based on the defined endpoints
export const { usePostResourceQuery } = createResource;

如果我想在另一个组件或另一个地方使用这个突变的相同结果,如何在不实际创建相同有效负载的情况下做到这一点?我是否必须将结果分派到可以存储它的不同切片,或者我们可以以某种方式引用从上述突变中收到的结果?

【问题讨论】:

    标签: typescript redux redux-toolkit


    【解决方案1】:

    理想情况下,突变(POST/PUT)不应返回任何静止状态,而应配置为使查询tags无效,以便可以重新触发获取。但是,我确实明白在某些情况下(为了获取数据),必须触发突变。

    因此,有两种方法可以实现相同的目的(访问突变的响应):

    1. 使用useMutation 时,突变结果将从rtk-query's 存储键中删除,即。 api 一旦组件卸载(基本上取消订阅)。因此,唯一的选择是将结果保存在单独的存储键(切片)中,以便稍后引用。
      const handleSubmit = async () => {
        try {
          const data = await mutationFn(PAYLOAD_BODY).unwrap();
          dispatch(SAVE_MUTATION_RESULT(data)); // save the results
        } catch(err) {
          console.error(err);
        }
      };
      
      1. 使用fixedCacheKey选项标记突变并使用dipatch操作方法触发突变,基本上解释为subscribed然后让订阅生效(不要取消订阅),这样响应就留在rtk-query's 存储密钥 (api),您可以在需要时查询它。
      const subcription = dispatch(createResource.endpoints.postResource.initiate(PAYLOAD_BODY, {
          fixedCacheKey: "postResource",
      }));
      
      // unsubscribe carefully, (so that don't endup removing the result from store)
      subcription.unsubscribe()
      

      现在,要获得响应,在任何其他组件中,可能在同一页面或完全不同的路由上,使用相同的键查询:

      const  [, {data}] = useMutation({
          fixedCacheKey: "postResource",
      })
      

      如果存储中存在突变及其结果,您将取回数据。

      有用的链接:

      谢谢, 马尼什

    【讨论】:

      猜你喜欢
      • 2022-08-05
      • 2022-08-09
      • 2021-11-21
      • 2021-10-12
      • 1970-01-01
      • 1970-01-01
      • 2021-03-03
      • 2017-11-21
      • 1970-01-01
      相关资源
      最近更新 更多