@@ -4,10 +4,10 @@ import { liteClient } from 'algoliasearch/lite';
44import { Hits } from 'react-instantsearch' ;
55import { InstantSearchNext } from 'react-instantsearch-nextjs' ;
66import { type SearchClient , type UiState } from 'instantsearch.js' ;
7+ import { useMemo , useEffect , useState } from 'react' ;
78import { SearchHit } from './SearchHit' ;
89import { SearchBox } from './SearchBox' ;
910import { SearchResultsHeader } from './SearchResultsHeader' ;
10- import { useMemo } from 'react' ;
1111import { NoResultsBoundary } from './NoResultsBoundary' ;
1212import { SearchPagination } from './SearchPagination' ;
1313
@@ -26,13 +26,14 @@ export const Search = ({
2626 noResultsErrorText = '' ,
2727 noResultsErrorTitle = '' ,
2828} : SearchProps ) => {
29+ const [ key , setKey ] = useState ( 'search-component' ) ;
2930 const numSuggestions = useMemo ( ( ) => parseInt ( suggestionsAmount , 10 ) || 0 , [ suggestionsAmount ] ) ;
30- const algoliaClient = liteClient (
31+ const algoliaClient = useMemo ( ( ) => liteClient (
3132 process . env . NEXT_PUBLIC_ALGOLIA_APP_ID ,
3233 process . env . NEXT_PUBLIC_ALGOLIA_SEARCH_API_KEY ,
33- ) ;
34+ ) , [ ] ) ;
3435
35- const searchClient = {
36+ const searchClient = useMemo ( ( ) => ( {
3637 ...algoliaClient ,
3738
3839 search ( requests : any [ ] ) {
@@ -54,13 +55,25 @@ export const Search = ({
5455
5556 return algoliaClient . search ( requests ) ;
5657 } ,
57- } ;
58+ } ) , [ algoliaClient ] ) ;
59+
60+ // This is a workaround to reset the InstantSearch state when the component is unmounted and remounted,
61+ // which can happen when navigating between pages in Next.js. By changing the key of the
62+ // InstantSearch component, we force it to reset its state.
63+ useEffect ( ( ) => {
64+ // eslint-disable-next-line react-hooks/set-state-in-effect
65+ setKey ( `search-component-${ Date . now ( ) } ` ) ;
66+ } , [ ] ) ;
5867
5968 return (
6069 < InstantSearchNext
70+ key = { key }
6171 indexName = { process . env . NEXT_PUBLIC_ALGOLIA_INDEX_NAME }
6272 searchClient = { searchClient as SearchClient }
6373 insights
74+ future = { {
75+ preserveSharedStateOnUnmount : false ,
76+ } }
6477 routing = { {
6578 router : {
6679 cleanUrlOnDispose : false ,
@@ -70,8 +83,8 @@ export const Search = ({
7083 stateToRoute ( uiState ) {
7184 const indexUiState = uiState [ process . env . NEXT_PUBLIC_ALGOLIA_INDEX_NAME ] ;
7285 return {
73- q : indexUiState . query ,
74- page : indexUiState . page ,
86+ q : indexUiState ? .query ,
87+ page : indexUiState ? .page ,
7588 } as UiState ;
7689 } ,
7790 routeToState ( routeState ) {
0 commit comments