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' ;
3
7
4
- function makeAdapter ( ) {
8
+ function makeAdapter ( { onChange } : { onChange ( ) : void } ) : QueryParamAdapter {
5
9
const adapter = {
6
10
replace ( location : PartialLocation ) {
7
11
window . history . replaceState ( location . state , '' , location . search || '?' ) ;
12
+ onChange ( ) ;
8
13
} ,
9
14
push ( location : PartialLocation ) {
10
15
window . history . pushState ( location . state , '' , location . search || '?' ) ;
16
+ onChange ( ) ;
11
17
} ,
12
18
get location ( ) {
13
19
return window . location ;
@@ -24,8 +30,17 @@ function makeAdapter() {
24
30
export const WindowHistoryAdapter : QueryParamAdapterComponent = ( {
25
31
children,
26
32
} ) => {
33
+ const handleURLChange = ( ) =>
34
+ setAdapter ( makeAdapter ( { onChange : handleURLChange } ) ) ;
27
35
// 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
+ } , [ ] ) ;
29
44
30
45
return children ( adapter ) ;
31
46
} ;
0 commit comments