From bcb93dc76a06411b11f9c33b5362cba9dfbc9cef Mon Sep 17 00:00:00 2001 From: SySagar Date: Tue, 27 Feb 2024 17:19:35 +0530 Subject: [PATCH] feat: debouncing --- src/app/events/components/EventList.jsx | 12 +++++++++--- src/hooks/useDebounce.js | 17 +++++++++++++++++ 2 files changed, 26 insertions(+), 3 deletions(-) create mode 100644 src/hooks/useDebounce.js diff --git a/src/app/events/components/EventList.jsx b/src/app/events/components/EventList.jsx index c811c21..84eab79 100644 --- a/src/app/events/components/EventList.jsx +++ b/src/app/events/components/EventList.jsx @@ -9,6 +9,7 @@ import EventCard from "./EventCard"; import useDatePicker from "../../../shared/store/useDatePicker"; import { useEffect, useState } from "react"; import { HighlightOff } from "@mui/icons-material"; +import { useDebounce } from "../../../hooks/useDebounce"; const datalist1 = [ { @@ -37,6 +38,7 @@ export default function EventList() { const [result, setResult] = useState([]); const [value, setValue] = useState(""); const pickedDate = useDatePicker((state) => state.pickedDate); + const debouncedQuery = useDebounce(value, 100); useEffect(() => { if (pickedDate !== "") { @@ -49,10 +51,10 @@ export default function EventList() { } }, [pickedDate]); - const filterDataList = () => { - if (value.trim() === "" && pickedDate === "") { + const filterDataList = (debouncedQuery) => { + if (debouncedQuery === "" && pickedDate === "") { setResult(totalData); - } else if (pickedDate !== "" && value === "") { + } else if (pickedDate !== "" && debouncedQuery === "") { setResult([]) const filtered = totalData.filter( (item) => @@ -69,6 +71,10 @@ export default function EventList() { } }; + useEffect(() => { + filterDataList(debouncedQuery); + }, [debouncedQuery]); + return ( { + const [debouncedValue, setDebouncedValue] = useState(value); + + useEffect(() => { + const handler = setTimeout(() => { + setDebouncedValue(value); + }, delay); + + return () => { + clearTimeout(handler); + }; + }, [value, delay]); + + return debouncedValue; +};