Skip to content

Commit

Permalink
[finished 187584874] seller delete item
Browse files Browse the repository at this point in the history
  • Loading branch information
solangeihirwe03 committed Aug 4, 2024
1 parent 8bd264f commit 2a65f58
Show file tree
Hide file tree
Showing 5 changed files with 99 additions and 24 deletions.
24 changes: 23 additions & 1 deletion src/components/product/SellerProduct.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,8 @@ import { PuffLoader } from 'react-spinners';
import { Meta } from '../Meta';
import { toast } from 'react-toastify';
import { getErrorMessage } from '../../utils/axios/axiosInstance';
import { deleteItem } from '../../store/features/product/sellerCollectionProductsSlice';
import ConfirmModal from './ConfirmModal';

const initialProductState: ISingleProduct = {
id: "",
Expand Down Expand Up @@ -42,6 +44,10 @@ const SellerProduct = ({ productId }: { productId: string }) => {
const [isImagesUpdated, setIsImagesUpdated] = useState<boolean>(false);
const [isThereAnyUpdate, setIsThereAnyUpdate] = useState<boolean>(false);

const [showConfirm, setShowConfirm] = useState(false);
const [itemToDelete, setItemToDelete] = useState<string | null>(null);


useEffect(() => {
if (isUpdate && isUpdateSuccess && !updateError) {
toast.success(`Product ${isAdd ? "added" : "updated"}`)
Expand Down Expand Up @@ -118,6 +124,14 @@ const SellerProduct = ({ productId }: { productId: string }) => {
}
};

const handleDelete = async () => {
if (updatedProduct) {
await dispatch(deleteItem(itemToDelete));
setShowConfirm(false);
navigate('/seller/products');
}
};

if (isLoading) {
return (
<div className="loader">
Expand Down Expand Up @@ -145,7 +159,7 @@ const SellerProduct = ({ productId }: { productId: string }) => {
<button disabled={!isThereAnyUpdate && !isImagesUpdated} className={`edit-btn ${!isThereAnyUpdate && !isImagesUpdated && 'disabled'}`} onClick={handleSaveOrAdd}>
<FaSave /> {isAdd ? "ADD" : "UPDATE"}
</button>
{!isAdd && <button className='delete-btn'><FaTrash /> Delete</button>}
{!isAdd && <button className='delete-btn' onClick={() => { setShowConfirm(true); setItemToDelete(productId); }}><FaTrash /> Delete</button>}
</div>
</div>

Expand Down Expand Up @@ -228,6 +242,14 @@ const SellerProduct = ({ productId }: { productId: string }) => {
</ContentCard>
</ContentCard>
</div>

<ConfirmModal
isOpen={showConfirm}
title="Are you sure"
message={`Deleting this product <i>${product?.name}</i> will be permanently removed from the system. This can't be undone!`}
onConfirm={handleDelete}
onCancel={() => setShowConfirm(false)}
/>
</div>
</div>
</>
Expand Down
43 changes: 41 additions & 2 deletions src/pages/seller/SellerCollection.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@
import React, { useEffect, useState } from 'react'
import Table from '../../components/table/Table';
import { useAppDispatch, useAppSelector } from '../../store/store';
import { fetchSellerCollectionProduct } from '../../store/features/product/sellerCollectionProductsSlice';
import { fetchSellerCollectionProduct, deleteItem, removeItem } from '../../store/features/product/sellerCollectionProductsSlice';
import Zoom from '@mui/material/Zoom';
import Tooltip from '@mui/material/Tooltip';
import DeleteIcon from '@mui/icons-material/Delete';
Expand All @@ -22,6 +22,13 @@ import { FaEye, FaPlusCircle } from 'react-icons/fa';
import { ISingleProductInitialResponse } from '../../utils/types/store';
import { resetUpdateState, updateSellerProductStatus } from '../../store/features/product/sellerProductSlice';
import { toast } from 'react-toastify';
import ConfirmModal from '../../components/product/ConfirmModal';

interface DeleteItemState {
id: any;
name: string;
}

export default function SellerCollection() {
const navigate = useNavigate()
const dispatch = useAppDispatch();
Expand All @@ -33,6 +40,26 @@ export default function SellerCollection() {
dispatch(fetchSellerCollectionProduct())
}, [dispatch]);

const [showConfirm, setShowConfirm] = useState(false);
const [itemToDelete, setItemToDelete] = useState<DeleteItemState | null>(null);


const handleDelete = async () => {
try {
setShowConfirm(false)
dispatch(removeItem(itemToDelete.id))
await dispatch(deleteItem(itemToDelete.id)).unwrap();
dispatch(fetchSellerCollectionProduct());
setItemToDelete(null)
} catch (error) {
console.error('Error deleting item:', error);
}finally{
if(isSuccess)
toast.success(message)
}
};


useEffect(() => {
if (isUpdate && isUpdateSuccess) {
toast.success(updateMessage);
Expand Down Expand Up @@ -69,7 +96,7 @@ export default function SellerCollection() {
</IconButton>
</Tooltip>
<Tooltip TransitionComponent={Zoom} title="Delete" arrow>
<IconButton>
<IconButton onClick={() => { setShowConfirm(true); setItemToDelete({ id: product.id, name: product.name }); }}>
<DeleteIcon className='icon__delete' />
</IconButton>
</Tooltip>
Expand Down Expand Up @@ -102,6 +129,8 @@ export default function SellerCollection() {
setOpen(false);
};

const popupMessage = `Deleting this product <i>${itemToDelete?.name}</i> will be permanently removed from the system. This can't be undone!`;

return (
<div className='seller__main__container'>
<Meta title={`Seller Products`} />
Expand Down Expand Up @@ -162,6 +191,16 @@ export default function SellerCollection() {
</Button>
</DialogActions>
</Dialog>

{showConfirm && (
<ConfirmModal
isOpen={showConfirm}
title="Are you sure?"
message={popupMessage}
onConfirm={handleDelete}
onCancel={() => setShowConfirm(false)}
/>
)}
</div>
)
}
Expand Down
12 changes: 11 additions & 1 deletion src/store/features/product/productService.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -99,6 +99,15 @@ const addSellerProduct = async (newProductData: FormData) => {
}
}

const SellerDeleteItem = async(id: string)=>{
try{
const response = await axiosInstance.delete(`api/shop/seller-delete-product/${id}`);
return response.data
}catch(error){
throw new Error("failed to delete product")
}
}

const productService = {
fetchProducts,
fetchSingleProduct,
Expand All @@ -109,6 +118,7 @@ const productService = {
fetchSellerSingleProduct,
updateSellerProduct,
addSellerProduct,
updateSellerProductStatus
updateSellerProductStatus,
SellerDeleteItem
}
export default productService;
42 changes: 23 additions & 19 deletions src/store/features/product/sellerCollectionProductsSlice.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -18,29 +18,33 @@ const initialState: ISellerCollectionProductInitialResponse = {
message: ''
}

export const fetchSellerCollectionProduct = createAsyncThunk<ISellerCollectionProductResponse>("products/fetchSellerCollectionProducts", async (_,thunkApi) => {
export const fetchSellerCollectionProduct = createAsyncThunk<ISellerCollectionProductResponse>("products/fetchSellerCollectionProducts", async (_, thunkApi) => {
try {
const response = await productService.fetchSellerProducts();
console.log(response)
return response;
} catch (error) {
return thunkApi.rejectWithValue(getErrorMessage(error));
}
});

export const deleteItem = createAsyncThunk<ISellerCollectionProductResponse, string>("product/deleteProduct", async(id, thunkApi)=>{
try{
const response = await productService.SellerDeleteItem(id)
return response
} catch(error){
return thunkApi.rejectWithValue(error)
export const deleteItem = createAsyncThunk<ISellerCollectionProductInitialResponse, string>("product/deleteProduct", async (id, thunkApi) => {
try {
const response = await productService.SellerDeleteItem(id)
return response
} catch (error) {
return thunkApi.rejectWithValue(error)
}
})
})

const sellerCollectionProductsSlice = createSlice({
name: "sellerCollectionProducts",
initialState,
reducers: {},
reducers: {
removeItem: (state, action: any) => {
const itemId = action.payload
state.data.products = state.data?.products.filter((item) =>item.id !== itemId)
}
},
extraReducers: (builder) => {
builder
.addCase(fetchSellerCollectionProduct.pending, (state) => {
Expand All @@ -59,24 +63,24 @@ const sellerCollectionProductsSlice = createSlice({
state.isSuccess = false;
state.message = action.payload.message || null
})
.addCase(deleteItem.pending, (state)=>{
state.isLoading = true,
.addCase(deleteItem.pending, (state) => {
state.isError = false,
state.isSuccess = false
state.isSuccess = false
})
.addCase(deleteItem.fulfilled, (state, action: PayloadAction<ISellerCollectionProductResponse>)=>{
.addCase(deleteItem.fulfilled, (state, action: PayloadAction<any>) => {
state.isLoading = false,
state.isError = false,
state.data= action.payload.data,
state.isSuccess = true
state.message = action.payload.message
})
.addCase(deleteItem.rejected, (state, action: PayloadAction<any>)=>{
.addCase(deleteItem.rejected, (state, action: PayloadAction<any>) => {
state.isLoading = false,
state.isError = true,
state.message = action.payload,
state.isSuccess = false
state.isError = true,
state.message = action.payload,
state.isSuccess = false
});
}
})

export const {removeItem} = sellerCollectionProductsSlice.actions
export default sellerCollectionProductsSlice.reducer;
2 changes: 1 addition & 1 deletion webpack.dev.config.ts
Original file line number Diff line number Diff line change
Expand Up @@ -97,7 +97,7 @@ const config: Configuration = {
historyApiFallback: {
disableDotRule: true,
},
port: 5000,
port: 9000,
open: true,
hot: true,
},
Expand Down

0 comments on commit 2a65f58

Please sign in to comment.