import { useEffect, useRef, useState } from 'react' import { useDispatch } from 'react-redux' import Swal from 'sweetalert2' import Axios from '../../axios' import { Box, CircularProgress, Container, FormControl, MenuItem, Pagination, Select, Typography, Table, TableBody, TableCell, TableContainer, TableHead, TableRow, Paper, } from '@mui/material' import ShopCard from './shopCard' const Shop = () => { const [option, setOption] = useState('all') const [products, setProducts] = useState([]) const [categories, setCategories] = useState([]) const [loading, setLoading] = useState(true) const [currentPage, setCurrentPage] = useState(1) const [totalData, setTotalData] = useState(0) const itemsPerPage = 10 // Adjust this according to your requirements const nameRef = useRef('') const categoryRef = useRef('') const dispatch = useDispatch() const handleChange = (event) => { const selectedValue = event.target.value setOption(selectedValue) categoryRef.current = selectedValue === 'all' ? '' : selectedValue // Set to an empty string if "All" is selected setCurrentPage(1) // Reset to first page when filter changes } const getCategories = async () => { try { const response = await Axios.get('/api/category/getCategories') setCategories(response.data?.categories || []) // Assuming the response has a categories property } catch (err) { Swal.fire({ title: 'Error', text: 'Failed to fetch categories', icon: 'error', button: 'Retry', dangerMode: true, }) } } const getProductsData = async () => { setLoading(true) try { const response = await Axios.get('/api/product/getAll/user/', { params: { page: currentPage, show: itemsPerPage, name: nameRef.current || '', category: categoryRef.current || '', // Send category only if it's not empty }, }) setProducts(response.data?.products || []) setTotalData(response.data?.total_data || 0) } catch (err) { const msg = err?.response?.data?.msg || 'Something went wrong!' Swal.fire({ title: 'Error', text: msg, icon: 'error', button: 'Retry', dangerMode: true, }) } finally { setLoading(false) } } useEffect(() => { getCategories() // Fetch categories on component mount getProductsData() }, [currentPage, option]) const handlePageChange = (event, value) => { setCurrentPage(value) } return ( Categories {loading ? ( ) : ( <> Product Name Category Price Action {products?.map((product) => ( {product?.name} {product.category.categoryName} ₹{product.price} ))}
)}
) } export default Shop