1- import { useState } from 'react' ;
2- import { PartialLocation , QueryParamAdapterComponent } from 'use-query-params' ;
1+ import { useEffect , useState } from 'react' ;
2+ import {
3+ PartialLocation ,
4+ QueryParamAdapterComponent ,
5+ QueryParamAdapter ,
6+ } from 'use-query-params' ;
37
4- function makeAdapter ( ) {
8+ function makeAdapter ( { onChange } : { onChange ( ) : void } ) : QueryParamAdapter {
59 const adapter = {
610 replace ( location : PartialLocation ) {
711 window . history . replaceState ( location . state , '' , location . search || '?' ) ;
12+ onChange ( ) ;
813 } ,
914 push ( location : PartialLocation ) {
1015 window . history . pushState ( location . state , '' , location . search || '?' ) ;
16+ onChange ( ) ;
1117 } ,
1218 get location ( ) {
1319 return window . location ;
@@ -24,8 +30,17 @@ function makeAdapter() {
2430export const WindowHistoryAdapter : QueryParamAdapterComponent = ( {
2531 children,
2632} ) => {
33+ const handleURLChange = ( ) =>
34+ setAdapter ( makeAdapter ( { onChange : handleURLChange } ) ) ;
2735 // we use a lazy caching solution to prevent #46 from happening
28- const [ adapter ] = useState ( makeAdapter ) ;
36+ const [ adapter , setAdapter ] = useState ( ( ) =>
37+ makeAdapter ( { onChange : handleURLChange } )
38+ ) ;
39+
40+ useEffect ( ( ) => {
41+ window . addEventListener ( 'popstate' , handleURLChange ) ;
42+ return ( ) => window . removeEventListener ( 'popstate' , handleURLChange ) ;
43+ } , [ ] ) ;
2944
3045 return children ( adapter ) ;
3146} ;
0 commit comments