Skip to main content

useFuse

The useFuse hook is used to help with fuzzy search, also known as approximate string matching.

github
View source code
import { useFuse } from '@uhg-abyss/web/hooks/useFuse';

Usage​

The useFuse hook uses the Fuse.jsopens in a new window 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​

PropertyTypeDefault
isCaseSensitivebooleanfalse
includeScorebooleanfalse
includeMatchesbooleanfalse
minMatchCharLengthnumber1
shouldSortbooleantrue
findAllMatchesbooleanfalse
keysArray[]

Fuzzy matching options​

PropertyTypeDefault
locationnumber0
thresholdnumber0.6
distancenumber100
ignoreLocationbooleanfalse

Advanced options​

PropertyTypeDefault
getFnFunction(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.

Important

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 });
Table of Contents