algolia / react-instantsearch

⚡️ Lightning-fast search for React and React Native applications, by Algolia.
https://www.algolia.com/doc/guides/building-search-ui/what-is-instantsearch/react/
MIT License
1.97k stars 386 forks source link

fix(hooks): prevent widget cleanup on `<InstantSearch>` unmount #3590

Closed FabienMotte closed 2 years ago

FabienMotte commented 2 years ago

Summary

Context

Starting from v6.30.2, when the <InstantSearch> component is unmounted, one search request per widget is triggered. The PR https://github.com/algolia/react-instantsearch/pull/3561 introduces this regression.

This issue was originally reported here: https://github.com/algolia/react-instantsearch/issues/3586.

Details

Currently, when the <InstantSearch> component is unmounted, a cleanup is scheduled using a setTimeout.

https://github.com/algolia/react-instantsearch/blob/affcbb58ee5c63345cc9424ad8ab566f3a01c9f9/packages/react-instantsearch-hooks/src/lib/useInstantSearchApi.ts#L156-L162

The widgets also rely on the same strategy when they unmount.

https://github.com/algolia/react-instantsearch/blob/affcbb58ee5c63345cc9424ad8ab566f3a01c9f9/packages/react-instantsearch-hooks/src/lib/useWidget.ts#L75-L77

And since the widgets are unmounted first, the removeWidgets() function is called and triggers a new search.

https://github.com/algolia/react-instantsearch/blob/affcbb58ee5c63345cc9424ad8ab566f3a01c9f9/packages/react-instantsearch-hooks/src/lib/useWidget.ts#L40-L42

Solution

This PR introduces a temporary fix that relies on a boolean flag _preventWidgetCleanup on the InstantSearch instance:

This solution works but should be considered temporary because in the future the InstantSearch.js update API should solve this issue.

Tests

This PR adds two tests, covering these use-cases:

Result

When the <InstantSearch> component is unmounted, no search request is made.

codesandbox-ci[bot] commented 2 years ago

This pull request is automatically built and testable in CodeSandbox.

To see build info of the built libraries, click here or the icon next to each commit SHA.

Latest deployment of this branch, based on commit 3865b2507764e3c368f6288ed8293b90d93447ba:

Sandbox Source
react-instantsearch-app Configuration
hooks-example Configuration
netlify[bot] commented 2 years ago

Deploy Preview for react-instantsearch ready!

Name Link
Latest commit 3865b2507764e3c368f6288ed8293b90d93447ba
Latest deploy log https://app.netlify.com/sites/react-instantsearch/deploys/62f104cd3008910008f60e6d
Deploy Preview https://deploy-preview-3590--react-instantsearch.netlify.app/examples/hooks-e-commerce
Preview on mobile
Toggle QR Code...

QR Code

Use your smartphone camera to open QR code link.

To edit notification comments on pull requests, go to your Netlify site settings.