Skip to content

Commit

Permalink
fix: now using setQueryParams no longer causes page to jump (#3837)
Browse files Browse the repository at this point in the history
  • Loading branch information
nickytonline authored Aug 2, 2024
1 parent 6a0199f commit 6541971
Showing 1 changed file with 17 additions and 7 deletions.
24 changes: 17 additions & 7 deletions lib/utils/query-params.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6,18 +6,28 @@ import Router from "next/router";
* @param {Record<string, string>} params - An object containing key-value pairs of query parameters to set. Pass in `{}`(an empty object) to skip.
* @param {Array<string>} [paramsToRemove=[]] - An optional array of query parameter keys to remove from the URL. To skip use `[]`(an empty array).
* @param {string | undefined} [pathname] - An optional variable for providing the pathname to go to.
* @param {boolean} [scroll=false] - An optional boolean to enable or disable scrolling to the top of the page.
*/
function setQueryParams(params: Record<string, string>, paramsToRemove: Array<string> = [], pathname?: string) {
function setQueryParams(
params: Record<string, string>,
paramsToRemove: Array<string> = [],
pathname?: string,
scroll = false
) {
const presentQueryParams = deleteKeys(Router.query, paramsToRemove);

// Merge final query and set URL
Router.push({
pathname: pathname || Router.pathname,
query: {
...presentQueryParams,
...params,
Router.push(
{
pathname: pathname || Router.pathname,
query: {
...presentQueryParams,
...params,
},
},
});
undefined,
{ scroll }
);
}

function deleteKeys<T extends ParsedUrlQuery, K extends keyof T>(obj: T, keys: K[]): T {
Expand Down

0 comments on commit 6541971

Please sign in to comment.