0.1.1 • Published 9 months ago

use-filters-hook v0.1.1

Weekly downloads
-
License
MIT
Repository
github
Last release
9 months ago

useFilters Hook

A React hook to easily manage filters for data fetching or UI manipulation.

Table of Contents

Installation

Install using npm:

npm install use-filters-hook

Or with yarn:

yarn add use-filters-hook

Peer Dependencies: Ensure that you have react installed in your project.

Usage

First, import the useFilters hook:

import useFilters from "use-filters-hook"

Then, in your component:

const [currentFilters, dispatch] = useFilters(initialFilters, dispatchFunction)

API

Methods

MethodDescriptionExample Usage
addFilterAdd or update filters. Updates if a filter for a given field exists; adds if not.actions.addFilter({field: 'name', ...})
updateFiltersDirectly update the filter array.actions.updateFilters(newFilters)
clearFilterClear a specific filter by providing a field name. If no field is provided, clears all filters.actions.clearFilter('name')

Filter Anatomy

Each filter has the following structure:

PropertyTypeDescriptionOptional
fieldstringSpecifies the name of the field to filter on.No
labelstringAn optional display label for the filter.Yes
valueanySpecifies the value to filter by.No
conditionstringSpecifies the condition under which the filtering occurs.No

Example

function App() {
  const [filters, setFilters] = useState<IFilter[]>([])
  const [, { addFilter, updateFilters, clearFilter }] = useFilters(
    filters,
    setFilters
  )

  const onAdd = () => {
    addFilter({
      field: `Field ${Math.random()}`,
      condition: `Condition ${Math.random()}`,
      value: Math.random(),
    })
  }

  return (
    <>
      <button onClick={onAdd}>Add Filter</button>
      <button
        onClick={() =>
          updateFilters([
            {
              field: `Field ${Math.random()}`,
              condition: `Condition ${Math.random()}`,
              value: Math.random(),
            },
          ])
        }>
        Update Filter
      </button>
      <button onClick={() => clearFilter()}>Clear</button>
      Filters: {JSON.stringify(filters)}
    </>
  )
}

Contribution

Pull requests are welcome! For major changes, please open an issue first to discuss what you would like to change. Ensure to update tests as appropriate.


0.1.1

9 months ago

0.1.0

9 months ago