From 7bba1cdc222f393cd713e7df53ebd4e844a72d1f Mon Sep 17 00:00:00 2001 From: Sibunnayak Date: Fri, 18 Oct 2024 16:09:35 +0530 Subject: [PATCH] update --- src/views/Brands/Brands.js | 199 ++++++++++++++----------- src/views/Categories/categories.js | 232 +++++++++++++++-------------- src/views/Products/Products.js | 15 +- 3 files changed, 232 insertions(+), 214 deletions(-) diff --git a/src/views/Brands/Brands.js b/src/views/Brands/Brands.js index bed3291..0a0dd7d 100644 --- a/src/views/Brands/Brands.js +++ b/src/views/Brands/Brands.js @@ -1,4 +1,4 @@ -import React, { useState, useEffect } from "react"; +import React, { useState, useEffect, useRef, useCallback } from "react"; import axios from "axios"; import { isAutheticated } from "src/auth"; import { @@ -13,7 +13,8 @@ import { import CloseIcon from "@mui/icons-material/Close"; import { ClipLoader } from "react-spinners"; import swal from "sweetalert"; - +import { toast } from "react-hot-toast"; +import debounce from "lodash.debounce"; const style = { position: "absolute", top: "50%", @@ -28,54 +29,65 @@ const style = { const Brands = () => { const token = isAutheticated(); + const nameRef = useRef(); const [loading, setLoading] = useState(true); const [updating, setUpdating] = useState(true); - const [saveLoding, setSaveLoading] = useState(true); + const [saveLoading, setSaveLoading] = useState(true); const [edit, setEdit] = useState(false); - const [brandName, setbrandName] = useState(""); - const [brandId, setbrandId] = useState(""); - const [brand, setbrand] = useState([]); + const [brandName, setBrandName] = useState(""); + const [brandId, setBrandId] = useState(""); + const [brands, setBrands] = useState([]); const [itemPerPage, setItemPerPage] = useState(10); const [page, setPage] = useState(1); const [open, setOpen] = useState(false); - const [olderbrandName, setOlderBrandName] = useState(""); - + const [olderBrandName, setOlderBrandName] = useState(""); const handleOpen = () => setOpen(true); const handleClose = () => { setOpen(false); setEdit(false); - setbrandName(""); - setbrandId(""); + setBrandName(""); + setBrandId(""); }; const getBrands = async () => { try { - const response = await axios.get("/api/brand/getBrands"); + setLoading(true); // Set loading to true before fetching + const response = await axios.get("/api/brand/getBrands", { + params: { + page, + show: itemPerPage, + brandName: nameRef.current?.value || "", + }, // Include pagination and search + }); if (response.status === 200) { - setbrand(response.data.brands); - setLoading(false); + setBrands(response.data.brands); } } catch (error) { console.error("Failed to fetch brands:", error); + } finally { + setLoading(false); // Set loading to false after fetching } }; useEffect(() => { getBrands(); - }, []); + }, [page, itemPerPage]); // Trigger fetch when these values change const handleEditClick = (_id, brandName) => { setOpen(true); - setbrandName(brandName); - setbrandId(_id); + setBrandName(brandName); + setBrandId(_id); setOlderBrandName(brandName); setEdit(true); }; const handleUpdate = async () => { - const filteredBrandNames = brand - .filter((brand) => brand.brandName.toLowerCase() !== olderbrandName.toLowerCase()) + const filteredBrandNames = brands + .filter( + (brand) => + brand.brandName.toLowerCase() !== olderBrandName.toLowerCase() + ) .map((brand) => brand.brandName.toLowerCase()); if (filteredBrandNames.includes(brandName.toLowerCase())) { @@ -97,7 +109,7 @@ const Brands = () => { headers: { Authorization: `Bearer ${token}` }, }); handleClose(); - swal("Success", "The brand was updated successfully!", "success"); + toast.success("Brand updated successfully"); getBrands(); } catch (err) { swal("Error", "Failed to update brand", "error"); @@ -120,7 +132,7 @@ const Brands = () => { await axios.delete(`/api/brand/delete/${_id}`, { headers: { Authorization: `Bearer ${token}` }, }); - swal("Success", "The brand was deleted successfully!", "success"); + toast.success("Brand deleted successfully"); getBrands(); } catch (err) { swal("Error", "Failed to delete brand", "error"); @@ -129,8 +141,12 @@ const Brands = () => { }); }; - const handleSavebrand = async () => { - if (brand.some((brand) => brand.brandName.toLowerCase() === brandName.toLowerCase())) { + const handleSaveBrand = async () => { + if ( + brands.some( + (brand) => brand.brandName.toLowerCase() === brandName.toLowerCase() + ) + ) { swal("Warning", "Brand already exists.", "error"); return; } @@ -148,7 +164,7 @@ const Brands = () => { await axios.post("/api/brand/add", formData, { headers: { Authorization: `Bearer ${token}`, - "Content-Type": "multipart/formdata", + "Content-Type": "multipart/form-data", }, }); handleClose(); @@ -161,8 +177,19 @@ const Brands = () => { } }; - const getPageCount = () => Math.max(1, Math.ceil(brand.length / itemPerPage)); + const getPageCount = () => + Math.max(1, Math.ceil(brands.length / itemPerPage)); + const debouncedSearch = useCallback( + debounce(() => { + setPage(1); + getBrands(); + }, 500), + [] + ); + const handleSearchChange = () => { + debouncedSearch(); + }; return (
@@ -191,9 +218,6 @@ const Brands = () => { textTransform: "capitalize", }} onClick={handleOpen} - // onClick={() => { - // navigate("/testimonial/new", { replace: true }); - // }} > Add New brand @@ -229,9 +253,9 @@ const Brands = () => { padding: "1rem", }} onChange={(e) => - setbrandName( + setBrandName( e.target.value.charAt(0).toUpperCase() + - e.target.value.slice(1) + e.target.value.slice(1) ) } /> @@ -249,7 +273,7 @@ const Brands = () => { p={2} display={"flex"} justifyContent={"right"} - // width={"500px"} + // width={"500px"} > {!edit && ( )} {edit && ( @@ -322,18 +346,17 @@ const Brands = () => {
-
+
@@ -356,16 +390,15 @@ const Brands = () => { style={{ background: "rgb(140, 213, 213)" }} > - Brand Name Action - {!loading && brand.length === 0 && ( + {!loading && brands.length === 0 && ( - +
No Data Available
@@ -377,61 +410,53 @@ const Brands = () => { ) : ( - brand && - brand - .slice( - (`${page}` - 1) * itemPerPage, - `${page}` * itemPerPage - ) - .map((item, i) => ( - - -
{item.brandName}
- - - - - - - )) + onClick={() => handleDelete(item._id)} + > + Delete + + + + )) )} diff --git a/src/views/Categories/categories.js b/src/views/Categories/categories.js index aa4c6c3..8a997d5 100644 --- a/src/views/Categories/categories.js +++ b/src/views/Categories/categories.js @@ -1,4 +1,4 @@ -import React, { useState, useEffect } from "react"; +import React, { useState, useEffect, useRef, useCallback } from "react"; import axios from "axios"; import { isAutheticated } from "src/auth"; import { @@ -13,7 +13,8 @@ import { import CloseIcon from "@mui/icons-material/Close"; import { ClipLoader } from "react-spinners"; import swal from "sweetalert"; - +import { toast } from "react-hot-toast"; +import debounce from "lodash.debounce"; const style = { position: "absolute", top: "50%", @@ -28,6 +29,7 @@ const style = { const Categories = () => { const token = isAutheticated(); + const nameRef = useRef(); const [loading, setLoading] = useState(true); const [updating, setUpdating] = useState(true); const [saveLoding, setSaveLoading] = useState(true); @@ -39,7 +41,6 @@ const Categories = () => { const [page, setPage] = useState(1); const [open, setOpen] = useState(false); const [olderCategoryName, setOlderCategoruName] = useState(""); - const handleOpen = () => setOpen(true); const handleClose = () => { @@ -53,24 +54,28 @@ const Categories = () => { const getCategories = async () => { try { + setLoading(true); const response = await axios.get("/api/category/getCategories", { - // headers: { - // Authorization: `Bearer ${token}`, - // }, + params: { + page, + show: itemPerPage, + categoryName: nameRef.current?.value || "", + }, // Include pagination and search }); if (response.status === 200) { setCategory(response?.data?.categories); - setLoading(false); } } catch (error) { console.error("Failed to fetch brands:", error); + } finally { + setLoading(false); // Set loading to false after fetching } }; useEffect(() => { getCategories(); - }, []); + }, [page, itemPerPage]); const handleEditClick = (_id, categoryName) => { setOpen(true); @@ -82,12 +87,14 @@ const Categories = () => { }; const handleUpdate = async () => { - const filteredArrayNames = category.filter( - (item) => item.categoryName.toLowerCase() !== olderCategoryName.toLowerCase()) - .map((item) => item.categoryName.toLowerCase() - ); + const filteredArrayNames = category + .filter( + (item) => + item.categoryName.toLowerCase() !== olderCategoryName.toLowerCase() + ) + .map((item) => item.categoryName.toLowerCase()); // console.log(filteredArrayNames, "filter"); - if(filteredArrayNames.includes(categoryName.toLowerCase())){ + if (filteredArrayNames.includes(categoryName.toLowerCase())) { swal({ title: "Warning", text: "Category already exists ", @@ -109,22 +116,16 @@ const Categories = () => { setUpdating(false); const formData = new FormData(); formData.append("categoryName", categoryName); -try{ - await axios - .patch(`/api/category/update/${categoryId}`, formData, { + try { + await axios.patch(`/api/category/update/${categoryId}`, formData, { headers: { Authorization: `Bearer ${token}`, }, - }) - handleClose(); - swal({ - title: "Congratulations!!", - text: "The category was updated successfully!", - icon: "success", - button: "OK", - }); - getCategories(); - }catch(err){ + }); + handleClose(); + toast.success("Category updated successfully"); + getCategories(); + } catch (err) { swal({ title: "", text: "Something went wrong!", @@ -132,7 +133,7 @@ try{ button: "Retry", dangerMode: true, }); - }finally{ + } finally { setUpdating(true); } }; @@ -148,33 +149,32 @@ try{ }).then(async (value) => { if (value === true) { try { - await axios - .delete(`/api/category/delete/${_id}`, { + await axios.delete(`/api/category/delete/${_id}`, { headers: { Authorization: `Bearer ${token}`, }, }); - swal({ - title: "Congratulations!!", - text: "The category was deleted successfully!", - icon: "success", - button: "OK", - }); - getCategories(); - }catch(err) { - swal({ - title: "", - text: "Something went wrong!", - icon: "error", - button: "Retry", - dangerMode: true, - }); + toast.success("Category deleted successfully"); + getCategories(); + } catch (err) { + swal({ + title: "", + text: "Something went wrong!", + icon: "error", + button: "Retry", + dangerMode: true, + }); + } } - }}); + }); }; const handleSaveCategory = async () => { - if(category.some((item) => item.categoryName.toLowerCase() === categoryName.toLowerCase())){ + if ( + category.some( + (item) => item.categoryName.toLowerCase() === categoryName.toLowerCase() + ) + ) { swal({ title: "Warning", text: "Category already exists ", @@ -198,23 +198,17 @@ try{ setLoading(true); const formData = new FormData(); formData.append("categoryName", categoryName); -try{ - await axios - .post("/api/category/add", formData, { + try { + await axios.post("/api/category/add", formData, { headers: { Authorization: `Bearer ${token}`, "Content-Type": "multipart/formdata", }, - }) - handleClose(); - swal({ - title: "Congratulations!!", - text: "The category was added successfully!", - icon: "success", - button: "OK", }); + handleClose(); + toast.success("Category added successfully"); getCategories(); - }catch(err){ + } catch (err) { swal({ title: "", text: "Something went wrong!", @@ -222,14 +216,24 @@ try{ button: "Retry", dangerMode: true, }); - }finally{ + } finally { setSaveLoading(true); } }; const getPageCount = () => { return Math.max(1, Math.ceil(category.length / itemPerPage)); }; + const debouncedSearch = useCallback( + debounce(() => { + setPage(1); + getCategories(); + }, 500), + [] + ); + const handleSearchChange = () => { + debouncedSearch(); + }; return (
@@ -258,9 +262,6 @@ try{ textTransform: "capitalize", }} onClick={handleOpen} - // onClick={() => { - // navigate("/testimonial/new", { replace: true }); - // }} > Add New Category @@ -298,7 +299,7 @@ try{ onChange={(e) => setCategoryName( e.target.value.charAt(0).toUpperCase() + - e.target.value.slice(1) + e.target.value.slice(1) ) } /> @@ -316,7 +317,7 @@ try{ p={2} display={"flex"} justifyContent={"right"} - // width={"500px"} + // width={"500px"} > {!edit && ( - - - - )) + onClick={() => handleDelete(item._id)} + > + Delete + + + + )) )} diff --git a/src/views/Products/Products.js b/src/views/Products/Products.js index b2192dc..ba48fad 100644 --- a/src/views/Products/Products.js +++ b/src/views/Products/Products.js @@ -6,6 +6,7 @@ import { useNavigate } from "react-router-dom"; import { isAutheticated } from "src/auth"; import swal from "sweetalert"; import debounce from "lodash.debounce"; +import { toast } from "react-hot-toast"; const Products = () => { const token = isAutheticated(); const navigate = useNavigate(); @@ -138,12 +139,7 @@ const Products = () => { }, }) .then((res) => { - swal({ - title: "Deleted", - text: "Product Deleted successfully!", - icon: "success", - button: "ok", - }); + toast.success("Product deleted successfully!"); setSuccess((prev) => !prev); }) .catch((err) => { @@ -179,12 +175,7 @@ const Products = () => { }, }) .then((res) => { - swal({ - title: "Changed", - text: "Product status changed successfully!", - icon: "success", - button: "ok", - }); + toast.success("Product status updated successfully!"); setSuccess((prev) => !prev); }) .catch((err) => {