Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
25 changes: 22 additions & 3 deletions src/useQueryParam.ts
Original file line number Diff line number Diff line change
Expand Up @@ -32,6 +32,25 @@ export const useQueryParam = <D, D2 = D>(
): [D2 | undefined, (newValue: D, updateType?: UrlUpdateType) => void] => {
const { history, location } = React.useContext(QueryParamContext);

// ref with current version history object
const refHistory = React.useRef<typeof history>(history);
React.useEffect(
() => {
refHistory.current = history;
},
[history]
);

// ref with current version location object
const refLocation = React.useRef<typeof location>(location);
React.useEffect(
() => {
refLocation.current = location;
},
[location]
);

// read in the raw query
if (!rawQuery) {
rawQuery = React.useMemo(() => {
let pathname = {};
Expand Down Expand Up @@ -78,12 +97,12 @@ export const useQueryParam = <D, D2 = D>(

updateUrlQuery(
{ [name]: newEncodedValue },
location,
history,
refLocation.current,
refHistory.current,
updateType
);
},
[location]
[]
);

return [decodedValue, setValue];
Expand Down
22 changes: 20 additions & 2 deletions src/useQueryParams.ts
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,24 @@ export const useQueryParams = <QPCMap extends QueryParamConfigMap>(
): [DecodedValueMap<QPCMap>, SetQuery<QPCMap>] => {
const { history, location } = React.useContext(QueryParamContext);

// ref with current version history object
const refHistory = React.useRef<typeof history>(history);
React.useEffect(
() => {
refHistory.current = history;
},
[history]
);

// ref with current version location object
const refLocation = React.useRef<typeof location>(location);
React.useEffect(
() => {
refLocation.current = location;
},
[location]
);

// read in the raw query
const rawQuery = React.useMemo(
() => parseQueryString(location.search) || {},
Expand Down Expand Up @@ -56,9 +74,9 @@ export const useQueryParams = <QPCMap extends QueryParamConfigMap>(
);

// update the URL
updateUrlQuery(encodedChanges, location, history, updateType);
updateUrlQuery(encodedChanges, refLocation.current, refHistory.current, updateType);
},
[location]
[]
);

// no longer Partial
Expand Down