11import React , { useEffect , useState } from 'react' ;
2- import { useQueryParam , encodeJson , decodeJson } from 'use-query-params' ;
2+ import { encodeJson } from 'use-query-params' ;
3+ import { useQueryParamString } from 'react-use-query-param-string' ;
34import clsx from 'clsx' ;
45import { InstantSearch , Index , Configure } from 'react-instantsearch-dom' ;
56import { client } from '../../utils/algolia' ;
@@ -17,26 +18,19 @@ const environment = process.env.GATSBY_ALGOLIA_ENVIRONMENT;
1718
1819const DEBOUNCE_TIME = 400 ;
1920
20- const NullJsonParam = {
21- encode : ( obj : any | null | undefined ) => {
22- if ( ! obj ) return undefined ;
23- return encodeJson ( obj ) ;
24- } ,
25- decode : ( str : string | ( string | null ) [ ] | null | undefined ) => {
26- if ( ! str ) return undefined ;
27- return decodeJson ( str ) ;
28- } ,
29- } ;
30-
3121const Search = ( ) : React . ReactElement | null => {
3222 const { state, dispatch } = useSearchContext ( ) ;
3323 const [ debouncedSetState , setDebouncedSetState ] = useState < any | null > ( null ) ;
34-
35- const [ searchStateQS , setSearchStateQS ] = useQueryParam ( 'search' , NullJsonParam ) ;
24+ const [ searchText , setSearchText , initialized ] = useQueryParamString ( 'search' , '' ) ;
3625 const locale = currentLocale ( ) ;
3726 const { t } = useTranslation ( ) ;
3827 const searchScrollPosition = 'searchscrollposition' ;
3928
29+ const encodeSearchState = ( obj : any | null | undefined ) => {
30+ if ( ! obj ) return undefined ;
31+ return encodeJson ( obj ) ;
32+ }
33+
4034 useEffect ( ( ) => {
4135 const scrollpos = sessionStorage . getItem ( searchScrollPosition ) ;
4236 if ( scrollpos ) {
@@ -51,7 +45,8 @@ const Search = (): React.ReactElement | null => {
5145 setDebouncedSetState (
5246 setTimeout ( ( ) => {
5347 sessionStorage . setItem ( searchScrollPosition , window . scrollY . toString ( ) ) ;
54- setSearchStateQS ( updatedSearchState , 'replaceIn' ) ;
48+ const nextSearchText = encodeSearchState ( state . searchState ) as string ;
49+ setSearchText ( nextSearchText ) ;
5550 } , DEBOUNCE_TIME ) ,
5651 ) ;
5752 dispatch ( { type : 'set-search-state' , payload : updatedSearchState } ) ;
@@ -64,12 +59,13 @@ const Search = (): React.ReactElement | null => {
6459 } ;
6560
6661 useEffect ( ( ) => {
67- setSearchStateQS ( state . searchActive ? state . searchState : null , 'replaceIn' ) ;
62+ const nextSearchText = state . searchActive ? encodeSearchState ( state . searchState ) as string : '' ;
63+ setSearchText ( nextSearchText ) ;
6864 } , [ state . searchActive ] ) ;
6965
7066 useEffect ( ( ) => {
71- if ( searchStateQS ) {
72- dispatch ( { type : 'set-search-state' , payload : searchStateQS } ) ;
67+ if ( searchText && initialized ) {
68+ dispatch ( { type : 'set-search-state' , payload : { query : searchText } } ) ;
7369 dispatch ( { type : 'set-search-active' , payload : true } ) ;
7470 }
7571 document . addEventListener ( 'keydown' , handleEsc ) ;
0 commit comments