import { useFuse } from '@uhg-abyss/web/hooks/useFuse';Usage
The useFuse hook uses the Fuse.js library to help with fuzzy searching (more formally known as approximate string matching), which is the technique of finding strings that are approximately equal to a given pattern (rather than exactly).
Example with TextInput component
Fuse keys
Fuse Keys are a list of keys that will be searched. Keys can be used to search in an object array, a nested search, as well as a weighted search. When a weight isn't provided, it will default to 1.
Fuse config options
Listed below are options that can be added to the config provided by the Fuse.js library
Basic options
- isCaseSensitive: type boolean, default set to false
- includeScore: type boolean, default set to false
- includeMatches: type boolean, default set to false
- minMatchCharLength: type number, default set to 1
- shouldSort: type boolean, default set to true
- findAllMatches: type boolean, default set to false
- keys: type Array, default set to empty array
Fuzzy matching options
- location: type number, default is set to 0
- threshold: type number, default is set to 0.6
- distance: type number, default is set to 100
- ignoreLocation: type boolean, default is set to false
Advanced options
- getFn: type Function, default (obj: T, path: string | string[]) => string | string[]
Search object array example
const list = [ { title: "Old Man's War", author: 'John Scalzi', tags: ['fiction'], }, { title: 'The Lock Artist', author: 'Steve', tags: ['thriller'], },];
const config = { includeScore: true,
};const keys= ['author', 'tags'],
const fuse = useFuse({list, config, keys});
const result = fuse.search('tion');Expected Output:
[ { item: { title: "Old Man's War", author: 'John Scalzi', tags: ['fiction'], }, refIndex: 0, score: 0.03, },];Nested search example
You can search through nested values using dot notation, array notation, or by defining a per-key getFN function. It is important to note that the path has to point to a string, otherwise you will not get any results.
Example with Dot Notation:
const list = [ { title: "Old Man's War", author: { name: 'John Scalzi', tags: [ { value: 'American', }, ], }, }, { title: 'The Lock Artist', author: { name: 'Steve Hamilton', tags: [ { value: 'English', }, ], }, },];
const config = { includeScore: true,};
const keys = ['author.tags.value'];
const fuse = useFuse({ list, config, keys });
const result = fuse.search('engsh');Using getFN:
const config = { includeScore: true,};
const keys = [ { name: 'title', getFn: (book) => book.title }, { name: 'authorName', getFn: (book) => book.author.name },];
const fuse = useFuse({ list, config, keys });
const result = fuse.search({ authorName: 'Steve' });Expected output for both:
[ { item: { title: 'The Lock Artist', author: { name: 'Steve Hamilton', tags: [ { value: 'English', }, ], }, }, refIndex: 1, score: 0.4, },];Properties
useFuse({ list, config, keys });