Let's ensure that the delete functionality works correctly by integrating the delete operation more robustly into both the ProductList and productSlice.
ProductList Component
I've noticed your deleteProductById thunk is already set up in the productSlice. Let's utilize that thunk in the ProductList component to handle product deletions and immediately update the local state.
Here's the updated ProductList component with the delete functionality incorporated:
import React, { useEffect, useState } from 'react';
import { useDispatch, useSelector } from 'react-redux';
import { fetchProducts, updateProductById, deleteProductById } from '../features/products/productSlice';
import { Box, Card, CardContent, CardMedia, Grid, Typography, Button } from '@mui/material';
import EditProduct from './EditProduct';
const backendURL = 'http://localhost:8000';
const ProductList = () => {
const dispatch = useDispatch();
const { products, loading, error } = useSelector(state => state.products);
const [productToEdit, setProductToEdit] = useState(null);
const [localProducts, setLocalProducts] = useState([]);
useEffect(() => {
dispatch(fetchProducts());
}, [dispatch]);
useEffect(() => {
setLocalProducts(products);
}, [products]);
const handleEditClick = (product) => {
setProductToEdit(product);
};
const handleEditCancel = () => {
setProductToEdit(null);
};
const handleEditConfirm = (updatedProduct) => {
dispatch(updateProductById(updatedProduct)).then(() => {
setLocalProducts((prev) =>
prev.map((product) =>
product.product_Id === updatedProduct.productId ? { ...updatedProduct } : product
)
);
setProductToEdit(null);
});
};
const handleDelete = (productId) => {
if (window.confirm('Are you sure you want to delete this product?')) {
dispatch(deleteProductById(productId)).then(() => {
dispatch(fetchProducts()); // Re-fetch products to get the updated list
});
}
};
if (loading) {
return <Box sx={{ display: 'flex', justifyContent: 'center', alignItems: 'center', height: '100vh' }}>Loading...</Box>;
}
if (error) {
return <Box sx={{ padding: 2 }}>Error: {error.message}</Box>;
}
return (
<Box sx={{ padding: 2 }}>
<Grid container spacing={3}>
{localProducts.map((product) => (
<Grid item xs={12} sm={6} md={4} lg={3} key={product.product_Id}>
<Card sx={{ height: '100%' }}>
<CardMedia
component="img"
height="140"
image={`${backendURL}${product.imageGallery?.image1}` || ''}
alt="Product Image"
/>
<CardContent>
<Typography gutterBottom variant="h5" component="div">
{product.product_Name}
</Typography>
<Typography variant="body2" color="text.secondary">
{product.product_Description}
</Typography>
<Typography variant="body2" color="text.secondary">
Price: ${product.product_Price}
</Typography>
<Typography variant="body2" color="text.secondary">
Stock: {product.product_Stock}
</Typography>
{/* Additional product details */}
</CardContent>
<Box sx={{ display: 'flex', justifyContent: 'center', gap: 2, mt: 'auto' }}>
<Button variant="contained" color="primary" onClick={() => handleEditClick(product)} sx={{ fontSize: '0.8rem' }}>
Edit
</Button>
<Button variant="contained" color="error" onClick={() => handleDelete(product.product_Id)} sx={{ fontSize: '0.8rem' }}>
Delete
</Button>
</Box>
</Card>
</Grid>
))}
</Grid>
{productToEdit && (
<EditProduct
product={productToEdit}
onSave={handleEditConfirm}
onCancel={handleEditCancel}
/>
)}
</Box>
);
};
export default ProductList;
productSlice
Ensure that your deleteProductById thunk correctly updates the state:
import { createSlice, createAsyncThunk } from '@reduxjs/toolkit';
import { getAllProducts, updateProduct, deleteProduct } from '../../services/productService';
// Async thunk to fetch products
export const fetchProducts = createAsyncThunk('products/fetchProducts', async () => {
const data = await getAllProducts();
return data;
});
// Async thunk to update a product
export const updateProductById = createAsyncThunk(
'products/updateProductById',
async ({ productId, product_Name, product_Description, product_Price, product_Stock, product_isSale, category_Name, imageGallery_Id, image1, image2, image3, image4 }) => {
console.log("all:", productId, product_Name, product_Description, product_Price, product_Stock, product_isSale, category_Name, imageGallery_Id, image1, image2, image3, image4);
const cleanImages = (imageUrl) => {
try {
const url = new URL(imageUrl);
let pathname = url.pathname.replace('/media/', '');
return pathname; // This keeps only the pathname, removing domain and port
} catch (error) {
console.error('Invalid URL:', imageUrl, error);
return imageUrl; // Return as-is if it’s not a valid URL
}
};
const cleanedImage1 = cleanImages(image1);
const cleanedImage2 = cleanImages(image2);
const cleanedImage3 = cleanImages(image3);
const cleanedImage4 = cleanImages(image4);
const updatedProduct = await updateProduct(productId, {
product_Name,
product_Description,
product_Price,
product_Stock,
product_isSale,
category_Name,
imageGallery_Id,
image1: cleanedImage1,
image2: cleanedImage2,
image3: cleanedImage3,
image4: cleanedImage4,
});
return updatedProduct;
}
);
// Async thunk to delete a product
export const deleteProductById = createAsyncThunk(
'products/deleteProductById',
async (productId) => {
await deleteProduct(productId);
return productId;
}
);
// Initial state
const initialState = {
products: [],
loading: false,
error: null,
};
// Create the slice
const productSlice = createSlice({
name: 'products',
initialState,
reducers: {},
extraReducers: (builder) => {
builder
.addCase(fetchProducts.pending, (state) => {
state.loading = true;
state.error = null;
})
.addCase(fetchProducts.fulfilled, (state, action) => {
state.loading = false;
state.products = action.payload;
})
.addCase(fetchProducts.rejected, (state, action) => {
state.loading = false;
state.error = action.error.message;
})
.addCase(updateProductById.pending, (state) => {
state.loading = true;
state.error = null;
})
.addCase(updateProductById.fulfilled, (state, action) => {
state.loading = false;
const index = state.products.findIndex((product) => product.product_Id === action.payload.product_Id);
if (index !== -1) {
state.products[index] = action.payload;
}
})
.addCase(updateProductById.rejected, (state, action) => {
state.loading = false;
state.error = action.error.message;
})
.addCase(deleteProductById.pending, (state) => {
state.loading = true;
state.error = null;
})
.addCase(deleteProductById.fulfilled, (state, action) => {
state.loading = false;
state.products = state.products.filter((product) => product.product_Id !== action.payload);
})
.addCase(deleteProductById.rejected, (state, action) => {
state.loading = false;
state.error = action.error.message;
});
},
});
export default productSlice.reducer;
Summary of Changes:
- ProductList Component:
- Updated the
handleDelete function to re-fetch products after deleting a product.
- Ensured immediate update of local state for better UI responsiveness.
- productSlice:
- Already includes the delete functionality correctly; just ensure it is properly handling the state update.
This should make the delete functionality work seamlessly, reflecting changes immediately in the UI. If there are further issues, let me know!