algolia / autocomplete

🔮 Fast and full-featured autocomplete library
https://alg.li/autocomplete
MIT License
5.03k stars 329 forks source link

How can I catch source errors? #1248

Closed aldenquimby closed 4 months ago

aldenquimby commented 5 months ago

Description

Reproduction

Steps

  1. Create autocomplete with multiple algolia sources:

    autocomplete({
    getSources: () => [{
    sourceId: 'posts',
    getItems: ({ query }) => getAlgoliaResults({
      searchClient,
      queries: [{ query, index_name: 'posts' }],
    }),
    }, {
    sourceId: 'events',
    getItems: ({ query }) => getAlgoliaResults({
      searchClient,
      queries: [{ query, index_name: 'events' }],
    }),
    }],
    ...
    })
  2. Turn off your internet so all requests will fail

  3. Type into search input

Expected behavior

Actual behavior

Environment

dhayab commented 5 months ago

Hi, thanks for your report. There is no error catching for Algolia sources at the library level currently. As a workaround you can catch errors at the search client level and forward them to the source in place of result items:

const algoliaClient = algoliasearch(appId, apiKey);
const searchClient = {
  ...algoliaClient,
  search(queries) {
    return algoliaClient.search(queries).catch((error) => {
      return { results: [{ hits: [{ error }] }] };
    });
  },
};

You will then be able to detect the presence of item.error in your source's item template and show a message accordingly.

aldenquimby commented 4 months ago

@dhayab perfect, thank you!