JSPM

react-use-flexsearch

0.2.0-next.0
  • ESM via JSPM
  • ES Module Entrypoint
  • Export Map
  • Keywords
  • License
  • Repository URL
  • TypeScript Types
  • README
  • Created
  • Published
  • Downloads 7511
  • Score
    100M100P100Q124167F
  • License MIT

React hook to search a FlexSearch index

Package Exports

  • react-use-flexsearch

This package does not declare an exports field, so the exports above have been automatically detected and optimized by JSPM instead. If any package subpath is missing, it is recommended to post an issue to the original package (react-use-flexsearch) to support the "exports" field. If that is not possible, create a JSPM override to customize the exports field for this package.

Readme

react-use-flexsearch

React hook to search a FlexSearch index.

Status

npm version

Installation

npm install --save react-use-flexsearch

API

useFlexSearch(query: String, index: Index | String, store: Object, options: Object) => Object[]

The useFlexSearch hook takes your search query, index, and store and returns results as an array. Searches are memoized to ensure efficient searching.

Parameters

Name Type Description
query String The search query. As this value updates, the return value will be updated.
index Index | String The FlexSearch index. This can be an instance of a FlexSearch index or one that has been exported via Index.export.
store Object Object mapping a result id to an object of data.
options Object Search options passed to Index.search.

Example

The following example renders a text input and queries the FlexSearch index on form submission.

Note: Formik is used in the following example to handle form state, but is not required. As long as your query is passed as the first parameter, you can manage how to store it.

import React, { useState } from 'react'
import { useFlexSearch } from 'react-use-flexsearch'
import { Formik, Form, Field } from 'formik'

const index = /* a FlexSearch index */
const store = {
  1: { id: 1, title: 'Document 1' },
  2: { id: 2, title: 'Document 2' },
  3: { id: 3, title: 'Document 3' },
}

const SearchBar = () => {
  const [query, setQuery] = useState(null)
  const results = useFlexSearch(query, index, store)

  return (
    <div>
      <Formik
        initialValues={{ query: '' }}
        onSubmit={(values, { setSubmitting }) => {
          setQuery(values.query)
          setSubmitting(false)
        }}
      >
        <Form>
          <Field name="query" />
        </Form>
      </Formik>
      <h1>Results</h1>
      <ul>
        {results.map(result => (
          <li key={result.id}>{result.title}</li>
        ))}
      </ul>
    </div>
  )
}