How do I set Algolia to not return any results if the query is blank?
You could use the searchFunction
and check the underlying helper state
to check whether or not the query is empty. Based on that, you can show/hide the search results div.
var search = instantsearch({
[...],
searchFunction: function(helper) {
var homePage = $('.home-page');
var searchResults = $('.search-results');
if (helper.state.query === '') {
// empty query string -> hide the search results & abort the search
searchResults.hide();
homePage.show();
return;
}
// perform the regular search & display the search results
helper.search();
homePage.hide();
searchResults.show();
}
}
This is also documented on the official website.
@aseure's solution will result in the script return
ing upon clicking "x" in the input to clear the search query. The following achieves the goal without breaking anything:
const search = instantsearch({
/* other parameters */
searchFunction(helper) {
const container = document.querySelector('#results');
if (helper.state.query === '') {
container.style.display = 'none';
} else {
container.style.display = '';
}
helper.search();
}
});
The above example is taken from the documentation here: https://www.algolia.com/doc/guides/building-search-ui/going-further/conditional-display/js/#handling-empty-queries