algolia / instantsearch

⚡️ Libraries for building performant and instant search and recommend experiences with Algolia. Compatible with JavaScript, TypeScript, React and Vue.
https://www.algolia.com/doc/guides/building-search-ui/what-is-instantsearch/js/
MIT License
3.59k stars 503 forks source link

docs(guides): Handling empty queries uses deprecated searchFunction #6194

Closed sgilberg closed 1 month ago

sgilberg commented 1 month ago

🐛 Current behavior

The guide for handling empty queries currently suggests using searchFunction(helper) to conditionally hide results. This method is now deprecated, and it suggests using onStateChange instead. It would be helpful to update these instructions to use the new method, and to indicate how best to use onStateChange to achieve the same results.

🔍 Steps to reproduce

  1. Go to https://www.algolia.com/doc/guides/building-search-ui/going-further/conditional-display/js/#using-the-helper-state
  2. Try using code provided
  3. See this warning in console: "[InstantSearch.js]: The searchFunction option is deprecated. Use onStateChange instead."

Live reproduction

https://codesandbox.io/p/sandbox/epic-leaf-fk5f32?file=%2Fsrc%2Fapp.js

💭 Expected behavior

Strangely, I'm not seeing the console warning in the code sandbox version, but searchFunction is clearly marked as deprecated in the docs.

Package version

instantsearch.js 4.68.1

Operating system

macOS 14.4.1

Browser

Chrome 124.0.6367.201

Code of Conduct

Haroenv commented 1 month ago

That's right, we'll remove the option with searchFunction as it's not a good solution.

Haroenv commented 1 month ago

The alternative now listed on the documentation is:

hits({
  transformItems(items, results) {
    if (results.query === '') return [];
    return items
  }
});

Then of course you need to style the results accordingly using the empty template to display nothing

sgilberg commented 1 month ago

Hi @Haroenv thanks for this suggestion. The alternative code isn't working for me, still shows the default list of items. (It appears results.query is undefined). Based on the API reference it looks like it's missing the brackets around { results } in transformItems(items, { results }).

When I add those, it works, but then of course it shows the same text as the empty template, as you mention, which isn't ideal. I'm able to customize that though by setting the empty template, as below. It may help to include such a suggestion in the docs for this option:

hits({
  transformItems(items, { results }) {
    if (results.query === '') return [];
    return items;
  },
  templates: {
    empty(results, {html}) {
      if (results.query === '') return null;
      return html`No results found for "${results.query}"`;
    },
  }
});
Haroenv commented 1 month ago

Thanks that's right, I'll edit the docs again!