summaryrefslogtreecommitdiff
path: root/src/lib/ServiceSearch.tsx
blob: 853f3833c3c1bd163cbc71ce7428a83311e472b8 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
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 = (event: React.ChangeEvent<HTMLInputElement>) => setSearch(event.target.value);

  const updateQuery = (value: string) => {
    if (service.searchBy) {
      const newQuery = service.searchBy.reduce((acc, key) => {
        if (value) acc[`${key}[$regex]`] = value;
        else delete acc[`${key}[$regex]`];
        return acc;
      }, query);

      setQuery(newQuery);
    }
  };

  // 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} value={search} onChange={handleChange} />
    </div>
  );
};

export default ServiceSearch;