import { useState, useEffect } from "react"; import { useLocation, Link } from "react-router-dom"; import ProductForm from "../components/ProductForm"; import { X } from "lucide-react"; const Selling = () => { const [products, setProducts] = useState([]); const [showForm, setShowForm] = useState(false); const storedUser = JSON.parse(sessionStorage.getItem("user")); const [editingProduct, setEditingProduct] = useState({ name: "", price: "", description: "", categories: [], images: [], }); // Simulate fetching products from API/database on component mount useEffect(() => { const fetchProducts = async () => { try { // Replace with your actual API endpoint const response = await fetch( "http://localhost:3030/api/product/myProduct", { method: "POST", headers: { "Content-Type": "application/json", }, body: JSON.stringify({ userID: storedUser.ID, // Assuming you have userId defined elsewhere in your component }), }, ); if (!response.ok) { throw new Error("Network response was not ok"); } const datajson = await response.json(); setProducts(datajson.data); } catch (error) { console.error("Error fetching products:", error); // You might want to set an error state here } }; fetchProducts(); }, []); // Add userId to dependency array if it might change // Handle creating or updating a product const handleSaveProduct = () => { if (editingProduct.id) { // Update existing product setProducts( products.map((p) => (p.id === editingProduct.id ? editingProduct : p)), ); } else { // Create new product const newProduct = { ...editingProduct, id: Date.now().toString(), // Generate a temporary ID }; setProducts([...products, newProduct]); } // Reset form and hide it setShowForm(false); setEditingProduct({ name: "", price: "", description: "", categories: [], images: [], }); }; // Handle product deletion const handleDeleteProduct = (productId) => { if (window.confirm("Are you sure you want to delete this product?")) { setProducts(products.filter((p) => p.id !== productId)); } }; // Handle editing a product const handleEditProduct = (product) => { setEditingProduct({ ...product, images: product.images || [], // Ensure images array exists }); setShowForm(true); }; // Handle adding a new product const handleAddProduct = () => { setEditingProduct({ name: "", price: "", description: "", categories: [], images: [], }); setShowForm(true); }; return (

My Listings

{!showForm && ( )}
{showForm ? ( setShowForm(false)} /> ) : ( <> {products.length === 0 ? (

You don't have any listings yet

) : (
{products.map((product) => (
{product.image_url && product.image_url.length > 0 ? ( {product.Name} ) : (
No image
)}

{product.Name}

${product.Price}

{product.categories && product.categories.length > 0 && (
{product.CategoryID.map((category) => ( {category} ))}
)}

{product.Description}

))}
)} )}
); }; export default Selling;