summaryrefslogtreecommitdiff
diff options
context:
space:
mode:
authoreug-vs <eug-vs@keemail.me>2021-04-18 22:53:52 +0300
committereug-vs <eug-vs@keemail.me>2021-04-18 22:53:52 +0300
commit2644ca9596ad664c11326ec9c27b781e078da016 (patch)
tree7fdeb49604c55a54cfed6e286b819b6cf37c9966
parenta8f56532c9df74dd483aa360919422154442c911 (diff)
downloadcommercel-ui-2644ca9596ad664c11326ec9c27b781e078da016.tar.gz
feat: correctly integrate search and filters
-rw-r--r--src/lib/ServiceList.tsx2
-rw-r--r--src/lib/ServiceSearch.tsx33
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 && <ServiceSearch />}
{service.filters && <ServiceFilters />}
+ {service.searchBy && <ServiceSearch />}
</>
);
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<string>('');
const { query, setQuery } = useQuery();
const placeholder = `Искать ${service.name.toLowerCase()}`;
- const handleChange = _.debounce((event: React.ChangeEvent<HTMLInputElement>) => {
+ const handleChange = (event: React.ChangeEvent<HTMLInputElement>) => 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 (
<div className="mr-6 flex items-center">
- <InputBase placeholder={placeholder} onChange={handleChange} />
+ <InputBase placeholder={placeholder} value={search} onChange={handleChange} />
</div>
);
};