Skip to content

Commit 0987512

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

File tree

1 file changed

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

1 file changed

+11
-4
lines changed

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

Lines changed: 11 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,7 @@
1-
import { useState } from 'react';
2-
import { PartialLocation, QueryParamAdapterComponent } from 'use-query-params';
1+
import { useEffect, useState } from 'react';
2+
import { PartialLocation, QueryParamAdapterComponent, QueryParamAdapter } from 'use-query-params';
33

4-
function makeAdapter() {
4+
function makeAdapter(): QueryParamAdapter {
55
const adapter = {
66
replace(location: PartialLocation) {
77
window.history.replaceState(location.state, '', location.search || '?');
@@ -25,7 +25,14 @@ export const WindowHistoryAdapter: QueryParamAdapterComponent = ({
2525
children,
2626
}) => {
2727
// we use a lazy caching solution to prevent #46 from happening
28-
const [adapter] = useState(makeAdapter);
28+
const [adapter, setAdapter] = useState<QueryParamAdapter>(makeAdapter)
29+
30+
useEffect(() => {
31+
const handleUpdate = () => setAdapter(makeAdapter())
32+
33+
window.addEventListener('popstate', handleUpdate)
34+
return () => window.removeEventListener('popstate', handleUpdate)
35+
}, [])
2936

3037
return children(adapter);
3138
};

0 commit comments

Comments
 (0)