Add InstantSearch and Autocomplete to your search experience in just 5 minutes
A good starting point for building a comprehensive search experience is a straightforward app template. When crafting your application’s ...
Senior Product Manager
A good starting point for building a comprehensive search experience is a straightforward app template. When crafting your application’s ...
Senior Product Manager
The inviting ecommerce website template that balances bright colors with plenty of white space. The stylized fonts for the headers ...
Search and Discovery writer
Imagine an online shopping experience designed to reflect your unique consumer needs and preferences — a digital world shaped completely around ...
Senior Digital Marketing Manager, SEO
Winter is here for those in the northern hemisphere, with thoughts drifting toward cozy blankets and mulled wine. But before ...
Sr. Developer Relations Engineer
What if there were a way to persuade shoppers who find your ecommerce site, ultimately making it to a product ...
Senior Digital Marketing Manager, SEO
This year a bunch of our engineers from our Sydney office attended GopherCon AU at University of Technology, Sydney, in ...
David Howden &
James Kozianski
Second only to personalization, conversational commerce has been a hot topic of conversation (pun intended) amongst retailers for the better ...
Principal, Klein4Retail
Algolia’s Recommend complements site search and discovery. As customers browse or search your site, dynamic recommendations encourage customers to ...
Frontend Engineer
Winter is coming, along with a bunch of houseguests. You want to replace your battered old sofa — after all, the ...
Search and Discovery writer
Search is a very complex problem Search is a complex problem that is hard to customize to a particular use ...
Co-founder & former CTO at Algolia
2%. That’s the average conversion rate for an online store. Unless you’re performing at Amazon’s promoted products ...
Senior Digital Marketing Manager, SEO
What’s a vector database? And how different is it than a regular-old traditional relational database? If you’re ...
Search and Discovery writer
How do you measure the success of a new feature? How do you test the impact? There are different ways ...
Senior Software Engineer
Algolia's advanced search capabilities pair seamlessly with iOS or Android Apps when using FlutterFlow. App development and search design ...
Sr. Developer Relations Engineer
In the midst of the Black Friday shopping frenzy, Algolia soared to new heights, setting new records and delivering an ...
Chief Executive Officer and Board Member at Algolia
When was your last online shopping trip, and how did it go? For consumers, it’s becoming arguably tougher to ...
Senior Digital Marketing Manager, SEO
Have you put your blood, sweat, and tears into perfecting your online store, only to see your conversion rates stuck ...
Senior Digital Marketing Manager, SEO
“Hello, how can I help you today?” This has to be the most tired, but nevertheless tried-and-true ...
Search and Discovery writer
A friend and I recently brainstormed how we could support our local bands while Covid continued to limit their opportunities to play live shows. We came up with an idea for a website where bands could sell limited-edition poster prints and t-shirts. The website would be designed to create a sense of community and urgency by promoting new items as they became available on social media, also known as ‘drops’, similar to what the fashion brands and the sneaker world have succeeded in doing.
We chose Algolia as our main tool because it offers front-end libraries that make it easy to spin up an ecommerce site with a top-tier search and discovery experience for customers. We decided to leverage the search capabilities and modularity of InstantSearch for React. Here’s a rough diagram of what we wanted to build:
The goal of the project was to create a sense of urgency when new products get released. The technical challenge, therefore, was to display an up-to-the-second inventory to our users. Searching and retrieving information from Algolia indexes is lightning fast, providing as-you-type instant search results. On the other hand, updating the data on the back end can take a little more time. However, we discovered that if we were to update our index every time the inventory changed, it would have slowed down both the search results and the rendering times of some front-end components.
We’re going to look at how we were able to use and adapt InstantSearch to build an almost up-to-the-second search capability for an ecommerce website.
Algolia InstantSearch offers incredibly fast search results, and it allowed us to scan through designs quickly to create the desired sense of urgency. The Autocomplete functionality inside InstantSearch added discovery, as users see suggestions they might not have considered.
I wanted to build the site in React because it offers good choices for ecommerce design and cross-platform compatibility. InstantSearch for React is a library of pre-built front-end React widgets that make getting started with a site layout a very quick process. The component diagram above maps well to a few of these widgets:
If you don’t have an Algolia Index, create an account and app. We created a <SearchBox>
component that contains the first three widgets (SearchBox, RefinementList, and Autocomplete), and a <Hits>
component for the Hits widget, displaying our list of products. The <ProductDetail>
component uses our own data and code, since it doesn’t come from the Algolia index.
We had a problem with this design, though, which is that it requires us to update and retrieve data from our Algolia index constantly. As we mentioned above, Algolia indexes are optimized for retrieval. Their engine prioritizes search, with fast indexing a close second. We didn’t want to flood the server with index updates which could slow down the search, the rendering of <Hits>
, or limit the functionality in <SearchBox>
, all of which depend on super-fast data retrieval with every keystroke. We came up with a solution – separate our inventory data updates from our search processing, so that we could update the inventory without touching our main index.
We went back to our site mock-up, and found we could work around this problem by customizing the InstantSearch widgets
The solution that lets us have both as-you-type instant search results and instant inventory is to have two separate Algolia indexes. If you don’t already have an Algolia Index, create an account and app.
One of the indexes is a typical product index. The JSON looks like this:
[ { "objectID": 42, "title": "Return to Paranormal", "band": “Out In The Cold”, "designer": “Jamie Deer”, "introduction_date": “2021-09-23T18:25:43.511Z”, "sizes": [“adults”, “kids”, “pets”], "_tags": ["Seattle", "aliens", “punk”] } ]
This is just a simple record. Eventually, we will include more information in the index, such as links to the band and designer websites, image URLs, etc.
The second index is simpler:
[ { “objectID”: 42, “remaining_editions”: 18 } ]
Now we can update the smaller inventory index without impacting the main index used for <Hits>
.
Using two indexes also requires splitting up the UI into two separate components for each Hit result, but it’s a simple adjustment:
We moved the remaining_editions
number out of the <Hits>
component and into its own separate custom widget, which we rendered as a separate component, called <Inventory>
. Both indexes, and both components, use the same objectID
.
It’s important to note that we’re not making <Inventory>
a child of <Hits>
, because we need to keep the rendering of these two components separate. That’s why the <SearchPage>
component holds <SearchBox>
, <Hits>
, <Inventory>
, and <ProductDetail>
at the same level.
As you might have noticed, we rely on three data sources:
<Hits>
and <SearchBox>
components. The data in here is an extract from our back-office database (3), which gets updated regularly when product listings change.remaining_editions
attribute displayed in the <Inventory>
component. The remaining_editions
attribute comes from our back-office database (3).<ProductDetail>
component asynchronously, with the exception of remaining_editions
, which is displayed to the <Inventory>
component.We have two goals in this application: one, to offer “instant” inventory numbers, and two, to keep as-you-type instant search results enabled at all times. Here’s how we accomplish both goals.
Keeping InstantSearch fully available is non-negotiable. Customers can understand a couple of seconds of delay in inventory, but they won’t tolerate slow or glitchy search functionality. Here’s how we structure this part:
Hits
. <SearchPage>
component, we use React state hooks and create a setter method for setObjectIDs
that gets passed to the <Hits>
component. objectIDs
in an array with a handler method, then pass that back up to <SearchPage>
. useEffect()
hook in <Hits>
, but Algolia provides a method in InstantSearch that achieves the same goal: onSearchStateChange
. These steps get us the information we need from <Hits>
without interrupting the UI or data flow of the as-you-type InstantSearch functionality – we just plug in to the middle with our connected component and use a built-in method to trigger updates.
Code for SearchBox.js
:
import { InstantSearch } from 'react-instantsearch-dom'; import SearchBox from './SearchBox.js'; import CustomHits from './Hits.js'; import Inventory from './Inventory.js'; import ProductDetail from './ProductDetail.js'; const searchClient = algoliasearch('YourApplicationID', 'YourSearchOnlyAPIKey'); function SearchPage() { const [objectIDs, setObjectIDs] = useState([]); const [selectedObject, setSelectedObject] = useState({ objectID: null, }); return ( <React.Fragment> <InstantSearch indexName="product_index" searchClient={searchClient} searchState={{ query: '', }} onSearchStateChange={searchState => { if (searchState) { setObjectIDs(); } }} > <SearchBox /> <CustomHits objectIDs={objectIDs} setObjectIDs={setObjectIDs} selectedObject={selectedObject} setSelectedObject={setSelectedObject} /> <Inventory objectIDs={objectIDs} /> <ProductDetail selectedObject={selectedObject} /> </InstantSearch> </React.Fragment> ); } export default SearchPage;
Code for Hits.js
`:
import React from 'react'; import PropTypes from 'prop-types'; import { connectHits } from 'react-instantsearch-dom'; function Hits({ hits, objectIDs, setObjectIDs }) { const handleSearch = () => { hits.map(hit => objectIDs.push(hit.objectID)); setObjectIDs(hits); }; return ( <ol> {handleSearch} {hits.map(hit => ( <li key={hit.objectID}>{hit.name}</li> ))} </ol> ); } Hits.propTypes = { hits: PropTypes.arrayOf(PropTypes.object), objectIDs: PropTypes.arrayOf(PropTypes.string), setObjectIDs: PropTypes.func, }; const CustomHits = connectHits(Hits); export default CustomHits;
Now that we are set up to capture the objectIDs
, we need to set up our inventory updates. There are three separate situations where we will be calling our inventory index: two for the <Inventory>
component, and one within the <ProductDetail>
component.
In order to display up-to-the-minute inventory information, we need two data points: the array of objectIDs
for the current results in <Hits>
, and the most recent number from our inventory index. The objectIDs
are now held in <SearchPage>
, and update each time the searchState
changes, so passing them down into <Inventory>
is easy. To get the info from our inventory index, we use another built-in Algolia method: index.getObjects()
. This lets us go directly to the objects we want without having to create another InstantSearch instance.
Note that as of algoliasearch@4.0.0
, the getObject()
and getObjects()
methods are not available in the lite
build, which is the default import – you’ll just need to update the import statement.
Once we make the initial connection, setting up the second call to the inventory index is simple. We added a setInterval()
function inside a useEffect()
hook to call the inventory index every two seconds. That way, even if a user doesn’t update their search term, inventory numbers will continue to refresh rapidly, ensuring real-time inventory. We may adjust that interval in production, but that seemed fast enough for our purposes.
Code for Inventory.js
:
import React, { useEffect } from 'react'; import PropTypes from 'prop-types'; import algoliasearch from 'algoliasearch'; const searchClient = algoliasearch('YourApplicationID', 'YourSearchOnlyAPIKey'); function Inventory({ objectIDs }) { const index = searchClient.initIndex('inventory_index'); let results = index.getObjects(objectIDs); useEffect(() => { const timer = setInterval(() => { results = index.getObjects(objectIDs); }, 2000); return () => clearTimeout(timer); }, []); return ( <ol> {results.map(result => ( <li key={result.objectID}>Remaining: {result.remaining_editions}</li> ))} </ol> ); } Inventory.propTypes = { objectIDs: PropTypes.arrayOf(PropTypes.string), }; export default Inventory;
The code inside the <ProductDetail>
component is much the same. That component will fetch most of its data from our product database, a non-Algolia data source. For the inventory number, it will call the inventory_index
just as above, using only the objectID
of the selectedObject
. With this design, there should only be a very small lag, no more than two seconds, between the inventory number shown next to the product result in <Hits>
and the inventory number in the <ProductDetail>
component. With this in place, <ProductDetail>
will always show the more recent data.
Now we have a <SearchPage>
that shows near-instant inventory updates, while still allowing full use of as-you-type instant search results.
We envisioned this project as a way for independent artists and musicians to connect their social media presences with an ecommerce platform. As music fans ourselves, we’ve missed the sense of community and energy of the local music scene over the last couple of years. Our hope is that this site design will feel authentic and exciting enough to capture some of that energy.
Algolia’s quick-to-implement widgets and adaptable components make it easy to spin up prototypes. You may have other ideas of where an ‘instant inventory’ would be useful – Black Friday sales, maybe! We hope to hear about what you build with Algolia, and how it transforms your projects!
Powered by Algolia Recommend