urlSearchParams not updating the url

3.6k Views Asked by At

I am trying to add search and page to my url for searching and pagination on a page.

 const urlParams = new URLSearchParams(window.location.search);
if(!urlParams.has('search'){
   urlParams.append('search', question);
}
if(!urlParams.has('page'){
   urlParams.append('page', pageIndex);
}

This appears to do nothing to the actual url. But when I call urlParams.toString() then I can see that they have been added, but they are not in the actual url in the browser.

I'm using Chrome 107, so it should support it. Am I missing something?

The documentation has not helped me so far.

2

There are 2 best solutions below

1
On BEST ANSWER

Of course it does nothing with the actual URL, you are creating a URLParameters Object and updating it. what you are missing is:

window.loacation.search = urlParams.toString()

it will change the query string in the browser URL and reloads the page.

if you are not interested in reloading the page, you can use history DOM object

let url = new URL(window.location.href);
if(!(url.searchParams.has('search'))){
   url.searchParams.append('search', question);
}
if(!(url.searchParams.has('page'))){
   url.searchParams.append('page', pageIndex);
}
history.pushState({},'',url.href);

finally, if you want to update the page and search params anyway, you can use the url.searchParams.set() method, like:

url.searchParams.set('page', pageIndex);

it will append the parameter if it does not exist, and will update it if it does, without throwing exceptions.

0
On

You can try this way:

First, retrieve the current path. Then, append the urlParams to the retrieved path and use history.pushState() to set the new URL.

const question = "the question";
const pageIndex = 3;

const urlParams = new URLSearchParams(window.location.search);

if (! urlParams.has('search')) {
   urlParams.append('search', question);
}

if (! urlParams.has('page')) {
   urlParams.append('page', pageIndex);
}

const path = window.location.href.split('?')[0];
const newURL = `${path}?${urlParams}`;

history.pushState({}, '', newURL);

Sources: