我想创建一个购物车,其中包含用户添加的产品列表并将其保存在 localStorage 中。如果我们有此 RTK 查询代码,是否可以在 createApi() 中定义该购物车?如果没有,我怎样才能在另一个切片中使用它?
export const productApi = createApi({
reducerPath: "productApi",
baseQuery: fetchBaseQuery({ baseUrl: "http://127.0.0.1:8000/api/" }),
tagTypes: ["Products"],
endpoints: (builder) => ({
SingleProduct: builder.query<IProduct, number>({
query: (id) => `product/${id}/`,
providesTags: (result, error, id) => [{ type: "Products", id }],
}),
}),
});
如果无法直接将购物车操作添加到 createApi,我如何提取 SingleProduct 并在此切片中使用它?
const cartSlice = createSlice({
name: "cart",
initialState,
reducers: {
addToCart: (state, action: PayloadAction<{ id: number, qty: number }>) => {
const data = // what should i put here?
state.push(data);
localStorage.setItem("cartItems", JSON.stringify(state));
},
},
});