5

I want to create a cart that contain list of products that user added and save it in localStorage. if we have this code for RTK query is that possible to define that cart inside the createApi() ? if not, how can I use it in another slice?

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 }],
    }),
  }),
});

if not possible to add cart action directly to createApi how can I extract the SingleProduct and use it in this slice?

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));
    },
  },
});
sarem eskandary
  • 504
  • 4
  • 16

2 Answers2

1

i dont think the right place to do that is inside the slice reducer itself. reducer must be clean - only change state. and without side-effect code and externalities, like localstorage for example. i am confronting the same issue in RTK Query like you because in 'vanila redux' i used to do all these actions inside createAsyncThunk.

  • Your answer could be improved with additional supporting information. Please [edit] to add further details, such as citations or documentation, so that others can confirm that your answer is correct. You can find more information on how to write good answers [in the help center](/help/how-to-answer). – Community Apr 15 '23 at 10:36
0

The best way to achieve what you want is that create cartSlice separately, your cartSlice must be something like this:

const initialState = [];

const cartSlice = createSlice({
  name: "cart",
  initialState,
  reducers: {
    addToCart: async (state, action: PayloadAction<{ id: number, qty: number }>) => {
      const { id, qty } = action.payload;
      const response = await fetch(`http://127.0.0.1:8000/api/product/${id}/`);
      const product = await response.json();
      if (product) {
        state.push({ ...product, qty });
        localStorage.setItem("cartItems", JSON.stringify(state));
      }
    },
  },
});
Sunny
  • 708
  • 1
  • 4
  • 21