Skip to content

Commit a1d9c6a

Browse files
committed
fix: update adapter when window location is changed
1 parent b14c97e commit a1d9c6a

File tree

1 file changed

+19
-4
lines changed
  • packages/use-query-params-adapter-window/src

1 file changed

+19
-4
lines changed

packages/use-query-params-adapter-window/src/index.ts

Lines changed: 19 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -1,13 +1,19 @@
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() {
2430
export 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

Comments
 (0)