import React, { useContext } from 'react'; import { useHistory } from 'react-router-dom'; import _ from 'lodash'; import hooks from '../hooks/useAPIClient'; import useQuery from '../hooks/useQuery'; import ServiceContext, { Filter } from './ServiceContext'; import { SelectBase } from '../components/Select'; const getOptionLabel = (item: any, filter: Filter) => { const value = _.get(item, filter.as || filter.key); return filter.transform ? filter.transform(value) : value; }; const ServiceFilters: React.FC = () => { const service = useContext(ServiceContext); const { query, setQuery } = useQuery(); const history = useHistory(); const { data } = hooks[service.route].useList('', { revalidateOnMount: !_.isEmpty(query) }); const filters = service.filters?.map(filter => { const options = _ .uniqBy(data, 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 handleFilterChange = (key: string) => (event: React.ChangeEvent) => { const { value } = event.target; const updatedQuery = { ...query, [key]: value }; if (value === '-') delete updatedQuery[key]; setQuery(updatedQuery); }; const resetFilters = () => history.push(service.route); return (
{filters && !_.isEmpty(query) && ( Сбросить фильтры )} {filters?.map(filter => ( ))}
); }; export default ServiceFilters;