【问题标题】:What's the proper way to use RTK Query when dealing with multiple base URLS?处理多个基本 URL 时使用 RTK Query 的正确方法是什么?
【发布时间】:2021-10-08 08:58:11
【问题描述】:

到目前为止,我已经迁移到 RTK 并非常享受它,但我坚持的一件事是以下情况:

我们有(为了简单起见)两个端点:

并且网站本身托管在另一个域上。

我需要从客户端点获取数据,但为了更新某些内容,我需要对订单端点进行突变。起初我以为我应该为每个基本 URL 定义一个 createApi,但后来我很确定我不能有失效。我想让这个先前的突变使客户的数据无效,以便重新获取新数据。

这就是我想出的,但如果这是前进的道路,我想提出一些意见。

export const customerApi = createApi({
  reducerPath: "/../",
  baseQuery: fetchBaseQuery({ baseUrl: "https://www.domain-customer.com/" }),
  endpoints: (builder) => ({
// write provides tag stuff here
    getCustomerExample: builder.query({ query: (name) => `customer/${name}` }),
// please ignore the details of the mutation, I haven't practiced much with it yet.
    updateCustomer: builder.mutation({
      queryFn: async (name) => {
        const response = await fetch(
          `https://www.domain-order.com/updateCustomer`,
           {update mutation stuff here}
        );
        const data = await response.json();

        return { data };
      }
// write invalidate stuff here
    })
  })
});

这是解决问题的方法吗?还是应该有一个巨大的 createAPI 来保存所有的突变和查询?

【问题讨论】:

  • 请编辑问题以将其限制为具有足够详细信息的特定问题,以确定适当的答案。

标签: javascript redux react-redux redux-toolkit rtk-query


【解决方案1】:

一般来说,是的,如果数据连接到足以使它们失效,则应该有一个 createApi

请注意,虽然大多数示例仅显示对 baseQuery 下的某些内容的查询,但您也可以只从 query 返回包含完整域的 url 参数(或字符串)-fetchBaseQuery 100% 支持用例。

所以在你的情况下:

updateCustomer: builder.mutation({
      query: (name) => ({
        url: `https://www.domain-order.com/updateCustomer`,
        // update mutation stuff here
      })
      // write invalidate stuff here
    })

【讨论】:

    猜你喜欢
    • 2019-05-12
    • 1970-01-01
    • 2010-11-27
    • 2011-05-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-01-09
    • 1970-01-01
    相关资源
    最近更新 更多