From ee9762e76f723ba41fa8f6ef99dc4ce38dff6f5c Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Dafydd=20Ll=C5=B7r=20Pearson?= Date: Wed, 18 Sep 2024 14:29:16 +0100 Subject: [PATCH] feat: Add debounce to search --- .../components/Sidebar/Search/index.tsx | 33 ++++++++++++------- 1 file changed, 22 insertions(+), 11 deletions(-) diff --git a/editor.planx.uk/src/pages/FlowEditor/components/Sidebar/Search/index.tsx b/editor.planx.uk/src/pages/FlowEditor/components/Sidebar/Search/index.tsx index 15adbbe656..ce8ad62d5c 100644 --- a/editor.planx.uk/src/pages/FlowEditor/components/Sidebar/Search/index.tsx +++ b/editor.planx.uk/src/pages/FlowEditor/components/Sidebar/Search/index.tsx @@ -3,8 +3,9 @@ import Container from "@mui/material/Container"; import Typography from "@mui/material/Typography"; import { useFormik } from "formik"; import { useSearch } from "hooks/useSearch"; +import { debounce } from "lodash"; import { useStore } from "pages/FlowEditor/lib/store"; -import React, { useEffect } from "react"; +import React, { useEffect, useMemo } from "react"; import ChecklistItem from "ui/shared/ChecklistItem"; import Input from "ui/shared/Input"; @@ -12,8 +13,10 @@ import { ExternalPortalList } from "./ExternalPortalList"; import { DATA_FACETS } from "./facets"; import { NodeSearchResults } from "./NodeSearchResults"; +const DEBOUNCE_MS = 300; + interface SearchNodes { - input: string; + pattern: string; facets: typeof DATA_FACETS; } @@ -28,9 +31,9 @@ const Search: React.FC = () => { }, [orderedFlow, setOrderedFlow]); const formik = useFormik({ - initialValues: { input: "", facets: DATA_FACETS }, - onSubmit: ({ input }) => { - search(input); + initialValues: { pattern: "", facets: DATA_FACETS }, + onSubmit: ({ pattern }) => { + debouncedSearch(pattern); }, }); @@ -39,6 +42,14 @@ const Search: React.FC = () => { keys: formik.values.facets, }); + const debouncedSearch = useMemo( + () => debounce((pattern: string) => { + console.debug("Search term: ", pattern) + return search(pattern); + }, DEBOUNCE_MS), + [search] + ); + return (
@@ -52,11 +63,11 @@ const Search: React.FC = () => { Search this flow and internal portals { - formik.setFieldValue("input", e.target.value); + formik.setFieldValue("pattern", e.target.value); formik.handleSubmit(); }} inputProps={{ spellCheck: false }} @@ -66,10 +77,10 @@ const Search: React.FC = () => { id={"search-data-field-facet"} checked inputProps={{ disabled: true }} - onChange={() => {}} + onChange={() => { }} /> - {formik.values.input && ( + {formik.values.pattern && ( <>