1.0.3 • Published 1 year ago

@alexkuc/use-filters v1.0.3

Weekly downloads
-
License
MIT
Repository
github
Last release
1 year ago

Use Filters

useFilters is a React-based hook that allows to filter arbitary data. It is written in TypeScript to take advantage of generics. The hook is scalable as it supports nested filters and arbitary data type as well as filters. Implementation has also unit tests.

Installation

You can install this directly from npm registry via

npm i @alexkuc/use-filters

Dependencies

This hook was written against React v18 but is not bundled itself.

Primary dependencies are listed under dependencies in package.json. Example-related dependencies are listed under optionalDependencies. Source-specific dependencies are listed under devDependencies.

Usage

Usage is pretty straight forward:

const { getData, setData, filters, setFilters } = useFilters({ data, filters });

where data can be any value and filters is an object typeof FilterMapType:

type FilterMapType<DataValue> = {
  [key: string]: Filter<DataValue>;
  [key: number]: Filter<DataValue>;
  [key: symbol]: Filter<DataValue>;
};
type Filter<DataValue> = {
  checkData: (item: DataValue) => boolean;
  removeValue: (value: any) => void;
  addValue: (value: any) => void;
  setValues: (value: any | any[]) => void;
  resetValues: () => void;
};

You can view online examples here and their source code can be found here.

FunctionPurposeNotes
getDataget filtered datacustom getter
setDataset raw, unfiltered datauseState setter
filtersinternal state of filtersuseState value
setFilterssets filtersuseState setter

If your filters are not set initially but later via setFilters, you need to explicitly set filter type:

const { ... } = useFilters<DataType, FilterType>(data, {});

Internal filters are exposed to allow running events when filters are modified, e.g. useEffect(..., [filters]).