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
| Property | Type | Default |
|---|---|---|
isCaseSensitive | boolean | false |
includeScore | boolean | false |
includeMatches | boolean | false |
minMatchCharLength | number | 1 |
shouldSort | boolean | true |
findAllMatches | boolean | false |
keys | Array | [] |
Fuzzy matching options
| Property | Type | Default |
|---|---|---|
location | number | 0 |
threshold | number | 0.6 |
distance | number | 100 |
ignoreLocation | boolean | false |
Advanced options
| Property | Type | Default |
|---|---|---|
getFn | Function | (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.
The path must 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 });