Using Fuse.js With Nacelle
Last updated: May 9, 2024
The Fuse.js library provides users with an easy way to perform client-side search.
Installation
We'll start by creating a new React project, and installing Fuse.js (you can also use Yarn, or a CDN link):
npm install --save fuse.js Finally, we'll install the Nacelle SDK:
npm install @nacelle/storefront-sdkGetting Data
Once we have our dependencies installed, our next step is to retrieve our product data from Nacelle. This will be the Javascript array we'll search against. For most Nacelle users this step should look familiar:
async function getProducts() {
const client = newStorefront({
token,
storefrontEndpoint,
});
const productsResp = await client.products();
setProducts(productsResp);
}The code above will reach out to the Nacelle API, and retrieve all of the products in our space. Then it will set the products state using setProducts. Speaking of which, let's set up our states:
const [products, setProducts] = useState([]); // Array of products from Nacelle
const [searchResults, setSearchResults] = useState([]); // Array of results, used in next sectionSetting Up Search
Once we have an array of products we can begin to search through it. With Fuse.js, this can be as simple as:
import Fuse from "fuse.js";
function searchForProducts(query) {
const fuse = new Fuse(products, {
keys: ["content.title", "content.description"],
});
const results = fuse.search(query);
setSearchResults(results.map((result) => result.item));
}In the snippet above we started by importing Fuse.js:
import Fuse from "fuse.js";Then we created a new function searchForProducts that accepted a parameter: query. As you may have guessed, this is the search term.
function searchForProducts(query) {
...
}Inside the searchForProducts function we created a new Fuse object, and gave it two parameters. The first is the array we'll be searching in: products, and the second is the fields we want to search: title, and description.
const fuse = new Fuse(products, {
keys: ["content.title", "content.description"],
});Finally, we use the search method to get an array of results matching our query, and update searchResults state:
const results = fuse.search(query);
setSearchResults(results.map((result) => result.item));Next Steps
From here you can iterate through searchResults and display the results to your customers. You can also customize the types of results Fuse.js returns by looking at the available options.