watermarkchurch / clc-app-v2

0 stars 1 forks source link

Add search bar to Schedule tab #110

Closed gburgett closed 1 year ago

gburgett commented 1 year ago

Copy the search bar code from the staff directory.

gburgett commented 1 year ago

Not required:

If you want you can upgrade both our Search components using Fuse.js: https://fusejs.io/

Here's a React hook I wrote to use Fuse search:

import { useCallback, useMemo, useState } from "react"
import Fuse from 'fuse.js'
import { present } from "../lib/util/present"

export function useFuseSearch<TData>(
  data: TData[],
  options?: Fuse.IFuseOptions<TData>,
  deps?: React.DependencyList
) {
  const fuse = useMemo(
    () => {
      return new Fuse(data, {
        threshold: 0.2,
        ...options
      })
    },
    deps
  )

  const [query, setQuery] = useState<string>()
  const [results, setResults] = useState<Fuse.FuseResult<TData>[]>()

  const executeSearch = useCallback((newQuery: string, options?: Fuse.FuseSearchOptions) => {
    if (present(newQuery)) {
      const results = fuse.search(newQuery, options)
      console.log('fuse results', results)
      setResults(results)
    } else {
      setResults(undefined)
    }

    setQuery(newQuery)
  }, [fuse])

  return [
    results?.map((r) => r.item),
    executeSearch,
    {
      query,
      fuse,
      results
    }
  ] as const
}