From e371759af6c218f18edc7a7dca8ba7b55cc367fb Mon Sep 17 00:00:00 2001
From: eug-vs <eug-vs@keemail.me>
Date: Sat, 17 Apr 2021 14:55:08 +0300
Subject: feat: initialize filters based on query string

---
 src/lib/ServiceList.tsx | 34 +++++++++++++++++++---------------
 1 file changed, 19 insertions(+), 15 deletions(-)

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

diff --git a/src/lib/ServiceList.tsx b/src/lib/ServiceList.tsx
index 9b12d6b..5abae6b 100644
--- a/src/lib/ServiceList.tsx
+++ b/src/lib/ServiceList.tsx
@@ -2,42 +2,46 @@ import React, { useContext } from 'react';
 import { useHistory, useLocation } from 'react-router-dom';
 import _ from 'lodash';
 import Page from '../containers/Page';
-import ListTable, { Field } from '../components/ListTable';
+import ListTable from '../components/ListTable';
 import hooks from '../hooks/useAPIClient';
-import ServiceContext from './ServiceContext';
+import ServiceContext, { Filter } from './ServiceContext';
+import useQuery from '../hooks/useQuery';
 
-const getItemField = (item: any, field: Field) => {
-  const value = _.get(item, field.key);
-  return field.transform ? field.transform(value) : value;
+const getOptionLabel = (item: any, filter: Filter) => {
+  const value = _.get(item, filter.as || filter.key);
+  return filter.transform ? filter.transform(value) : value;
 };
 
 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(key => {
-    const field = _.find(service.tableFields, { key });
-    if (!field) return { key: '-', label: '-', options: [] };
-
-    const options = data?.map((item: any) => ({
-      key: _.get(item, field.key),
-      label: getItemField(item, field),
-    }));
+  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: field.label,
+      label: filter.label,
     });
 
-    return { ...field, options };
+    const value = _.get(query, filter.key);
+
+    return { ...filter, options, value };
   });
 
   const handleRowClick = (item: any) => {
-- 
cgit v1.2.3

