我正在使用Redux Toolkit createApi设置,并且遇到了createItem端点触发不必要的API调用以获取篮子的问题。
我的createItem突变会更新购物篮,并在响应中返回更新后的数据。为了确保缓存反映更新,我使用了带有“Basket”标记和“LIST”ID的invalidatesTags。
尽管在响应中提供了更新的篮子,但在createItem解析后会再次调用getBasket查询。这似乎是多余和不必要的,因为更新后的购物篮已经可用。
export const basketApi = createApi({
reducerPath: "basketApi",
baseQuery: fetchBaseQuery({
baseUrl: "https://localhost:5000/api/",
credentials: "include",
}),
tagTypes: ["Basket"],
endpoints: (builder) => ({
getBasket: builder.query<Basket, void>({
query: () => `basket`,
providesTags: [{ type: "Basket", id: "LIST" }],
}),
createItem: builder.mutation<Basket, { productId: number; qty?: number }>({
query: ({ productId, qty }) => ({
url: `Basket?productId=${productId}&quantity=${qty || 1}`,
method: "POST",
}),
invalidatesTags: [{ type: "Basket", id: "LIST" }],
}),
}),
});
当响应已经包括更新的篮子时,如何防止在createItem之后对getBasket进行不必要的API调用?
我找到了这种方法,但不确定在这里呼叫调度是否正确:
export const basketApi = createApi({
reducerPath: "basketApi",
baseQuery: fetchBaseQuery({
baseUrl: "https://localhost:5000/api/",
credentials: "include",
}),
tagTypes: ["Basket"],
endpoints: (builder) => ({
getBasket: builder.query<Basket, void>({
query: () => `basket`,
providesTags: [{ type: "Basket", id: "LIST" }],
}),
createItem: builder.mutation<Basket, { productId: number; qty?: number }>({
query: ({ productId, qty }) => ({
url: `Basket?productId=${productId}&quantity=${qty || 1}`,
method: "POST",
}),
invalidatesTags: (result) => {
store.dispatch(setBasket(result));
return [];
},
}),
}),
});