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-sdk
Getting 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 section
Setting Up Search
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));
}
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) {
...
}
const fuse = new Fuse(products, {
keys: ["content.title", "content.description"],
});
const results = fuse.search(query);
setSearchResults(results.map((result) => result.item));
Comments
0 comments
Please sign in to leave a comment.