From f3d3471e697d6ebede4fa584c8671fb686028381 Mon Sep 17 00:00:00 2001
From: eug-vs <eug-vs@keemail.me>
Date: Sat, 17 Apr 2021 16:42:30 +0300
Subject: refactor: move move filters to ServiceFilters

---
 src/lib/ServiceList.tsx | 44 +++-----------------------------------------
 1 file changed, 3 insertions(+), 41 deletions(-)

(limited to 'src/lib/ServiceList.tsx')

diff --git a/src/lib/ServiceList.tsx b/src/lib/ServiceList.tsx
index 9f6835a..ae17a9c 100644
--- a/src/lib/ServiceList.tsx
+++ b/src/lib/ServiceList.tsx
@@ -4,46 +4,20 @@ import _ from 'lodash';
 import Page from '../containers/Page';
 import ListTable from '../components/ListTable';
 import hooks from '../hooks/useAPIClient';
-import ServiceContext, { Filter } from './ServiceContext';
-import useQuery from '../hooks/useQuery';
-
-const getOptionLabel = (item: any, filter: Filter) => {
-  const value = _.get(item, filter.as || filter.key);
-  return filter.transform ? filter.transform(value) : value;
-};
+import ServiceContext from './ServiceContext';
+import ServiceFilters from './ServiceFilters';
 
 const ServiceList: React.FC = () => {
   const service = useContext(ServiceContext);
   const history = useHistory();
   const location = useLocation();
-  const query = useQuery();
   const { data } = hooks[service.route].useList(location.search);
-  const { data: unfilteredData } = hooks[service.route].useList('', { revalidateOnMount: !!location.search });
 
   const actions = service.actions || [{
     name: 'Добавить',
     route: `/${service.route}/add${location.search}`,
   }];
 
-  const filters = service.filters?.map(filter => {
-    const options = _
-      .uniqBy(unfilteredData, filter.key)
-      .map((item: any) => ({
-        key: _.get(item, filter.key),
-        label: getOptionLabel(item, filter),
-      }));
-
-    // Add default option
-    options?.unshift({
-      key: '-',
-      label: filter.label,
-    });
-
-    const value = _.get(query, filter.key);
-
-    return { ...filter, options, value };
-  });
-
   const handleRowClick = (item: any) => {
     const route = service.rowLink
       ? service.rowLink(item)
@@ -52,23 +26,11 @@ const ServiceList: React.FC = () => {
     history.push(route);
   };
 
-  const applyFilter = (key: string, value: string) => {
-    const updatedQuery = { ...query, [key]: value };
-    if (value === '-') delete updatedQuery[key];
-
-    const queryString = new URLSearchParams(updatedQuery);
-    history.push(`${service.route}?${queryString}`);
-  };
-
-  const resetFilters = () => history.push(service.route);
-
   return (
     <Page
       title={service.name}
       actions={actions}
-      filters={filters}
-      applyFilter={applyFilter}
-      resetFilters={resetFilters}
+      filters={<ServiceFilters />}
     >
       <ListTable items={data} fields={service.tableFields} handleRowClick={handleRowClick} />
     </Page>
-- 
cgit v1.2.3

