From 2644ca9596ad664c11326ec9c27b781e078da016 Mon Sep 17 00:00:00 2001 From: eug-vs Date: Sun, 18 Apr 2021 22:53:52 +0300 Subject: feat: correctly integrate search and filters --- src/lib/ServiceList.tsx | 2 +- src/lib/ServiceSearch.tsx | 33 ++++++++++++++++++++++++++++----- 2 files changed, 29 insertions(+), 6 deletions(-) diff --git a/src/lib/ServiceList.tsx b/src/lib/ServiceList.tsx index 8983bfa..be9a311 100644 --- a/src/lib/ServiceList.tsx +++ b/src/lib/ServiceList.tsx @@ -29,8 +29,8 @@ const ServiceList: React.FC = () => { const filters = ( <> - {service.searchBy && } {service.filters && } + {service.searchBy && } ); diff --git a/src/lib/ServiceSearch.tsx b/src/lib/ServiceSearch.tsx index b2509d3..853f383 100644 --- a/src/lib/ServiceSearch.tsx +++ b/src/lib/ServiceSearch.tsx @@ -1,29 +1,52 @@ -import React, { useContext } from 'react'; +import React, { useContext, useEffect, useMemo, useState } from 'react'; import _ from 'lodash'; import { InputBase } from '../components/Input'; import ServiceContext from './ServiceContext'; import useQuery from '../hooks/useQuery'; + const ServiceSearch: React.FC = () => { const service = useContext(ServiceContext); + const [search, setSearch] = useState(''); const { query, setQuery } = useQuery(); const placeholder = `Искать ${service.name.toLowerCase()}`; - const handleChange = _.debounce((event: React.ChangeEvent) => { + const handleChange = (event: React.ChangeEvent) => setSearch(event.target.value); + + const updateQuery = (value: string) => { if (service.searchBy) { const newQuery = service.searchBy.reduce((acc, key) => { - acc[`${key}[$regex]`] = event.target.value; + if (value) acc[`${key}[$regex]`] = value; + else delete acc[`${key}[$regex]`]; return acc; }, query); setQuery(newQuery); } - }, 250); + }; + + // Debounce updateQuery on search change + useEffect(() => { + const handler = setTimeout(() => { + updateQuery(search); + }, 300); + + return () => { + clearTimeout(handler); + }; + }, [search]); + + + // When querySearch changes externally, update search + const querySearch = useMemo(() => query[`${service.searchBy?.[0]}[$regex]`] || '', [query]); + useEffect(() => { + if (querySearch !== search) setSearch(querySearch); + }, [querySearch]); return (
- +
); }; -- cgit v1.2.3