krisk / Fuse

Lightweight fuzzy-search, in JavaScript
https://fusejs.io/
Apache License 2.0
17.79k stars 756 forks source link

How to use API response as index in React? #596

Closed ShahriarKh closed 2 years ago

ShahriarKh commented 2 years ago

I'm trying to implement Fuse in React (Next.js). My search functionality retrieves the index from API, so I need to create the Fuse instance without index and then use useState or something like that to replace the index.

My code is something like this:

const options = {
   keys: ["title"],
};

function handleSearch(term) {
   console.log(fuse.search(term));
}

export default function SearchSection() {
   return (
       <input onChange={(e) => handleSearch(e.target.value)} />
   );
}

And this is how I get the index (using graphql-request):

const { posts } = await request(CMS, POSTS);

Knowing these, where should I put the Fuse? Maybe something like this:

const fuse = new Fuse(posts, options)

But I don't know where I should put it... (I'm mostly confused with the await behavior)