Algolia InstantSearch Don't Show Listing if No Query (Vue.js)

August 19, 2020

Algolia InstantSearch will show a default listing even though no query is entered.

To prevent listing if there is no query

import algoliasearch from 'algoliasearch/lite'

// this setup is required to prevent search on empty query
const searchClient = {
  search(requests) {
    if (requests.every(({ params }) => !params.query)) {
     // return empty result if no query
     return Promise.resolve({
        results: requests.map(() => ({
          hits: [],
          nbHits: 0,
          nbPages: 0,
          processingTimeMS: 0,
        })),
      });
    }

    return algoliaClient.search(requests);
  },
};

export default {
  data() {
    return {
      /*
      searchClient: algoliasearch(
        '3P********', // Application ID
        '0a5f4c5c0b18********************'  // Search-Only API Key
      ),
       */
      searchClient
    }
  },
};

NOTE: Refer to Setup Algolia InstantSearch on Nuxt/Vue for complete code.

This work is licensed under a
Creative Commons Attribution-NonCommercial 4.0 International License.