在处理多个基本 URL 时使用 RTK 查询的正确方法是什么?



到目前为止,我已经迁移到RTK,并且非常喜欢它,但是有一件事我被困在了下面的情况:

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

  • www.domain-customer.com <-获取客户数据
  • www.domain-order.com <-可以在这里改变一些用户数据

网站本身托管在另一个域

我需要从客户端点获取数据,但为了更新某些事情我需要做一个突变的端点。起初,我认为我应该为每个基础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来保存所有的突变和查询?

一般来说,如果数据连接足够,您应该有一个单独的createApi

请注意,虽然大多数示例只是在baseQuery下显示查询,但您也可以从query返回包含完整域的url参数(或字符串)-fetchBaseQuery100%支持该用例。

所以在你的例子中:

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

最新更新