|
1 | 1 | /* eslint-disable */
|
2 | 2 | import { createSlice, createAsyncThunk, PayloadAction } from "@reduxjs/toolkit";
|
3 | 3 | import productService from "./productService";
|
4 |
| -import { IProduct, SearchCriteria } from "../../../utils/types/product"; |
| 4 | +import { IProduct, ISingleProduct, SearchCriteria } from "../../../utils/types/product"; |
5 | 5 | import { getErrorMessage } from "../../../utils/axios/axiosInstance";
|
6 | 6 |
|
7 | 7 | const initialState: { products: IProduct[] | null; isLoading: boolean; isError: boolean | null; isSuccess: boolean; message: string } = {
|
@@ -31,6 +31,15 @@ export const searchProduct = createAsyncThunk<IProduct, SearchCriteria>("product
|
31 | 31 | }
|
32 | 32 | );
|
33 | 33 |
|
| 34 | +export const deleteItem = createAsyncThunk<ISingleProduct, string>("product/deleteProduct", async(id, thunkApi)=>{ |
| 35 | + try{ |
| 36 | + const response = await productService.deleteItem(id) |
| 37 | + return response |
| 38 | + } catch(error){ |
| 39 | + return thunkApi.rejectWithValue(error) |
| 40 | + } |
| 41 | +}) |
| 42 | + |
34 | 43 | const productSlice = createSlice({
|
35 | 44 | name: "products",
|
36 | 45 | initialState,
|
@@ -68,6 +77,23 @@ const productSlice = createSlice({
|
68 | 77 | state.isError = true;
|
69 | 78 | state.message = action.payload;
|
70 | 79 | state.isSuccess = false;
|
| 80 | + }) |
| 81 | + .addCase(deleteItem.pending, (state)=>{ |
| 82 | + state.isLoading = true, |
| 83 | + state.isError = false, |
| 84 | + state.isSuccess = false |
| 85 | + }) |
| 86 | + .addCase(deleteItem.fulfilled, (state, action: PayloadAction<ISingleProduct>)=>{ |
| 87 | + state.isLoading = false, |
| 88 | + state.isError = false, |
| 89 | + state.products = state.products.filter(product => product.id !== action.payload.id), |
| 90 | + state.isSuccess = true |
| 91 | + }) |
| 92 | + .addCase(deleteItem.rejected, (state, action: PayloadAction<any>)=>{ |
| 93 | + state.isLoading = false, |
| 94 | + state.isError = true, |
| 95 | + state.products = action.payload, |
| 96 | + state.isSuccess = false |
71 | 97 | });
|
72 | 98 | }
|
73 | 99 | })
|
|
0 commit comments