So I stumpled over the need to add url parameters with search and page for respectively searching and pagination.
This I achived with UrlSearchParams
With this, I can check if a parameter exists, set a new one, update its value or delete it.
To Achieve this we start out with
const urlParams = new URLSearchParams(window.location.search);
With this we have a ready object to manipulate our url with.
if(typeof q !== 'undefined' && q !== ''){
urlParams.set('search', q);
}else{
urlParams.delete('search');
}
if(typeof pageIndex !== 'undefined' && pageIndex > 0){
urlParams.set('page', pageIndex);
}else{
urlParams.delete('page');
}
The above code, checks variables I have parsed to a function, before trying to set them, else it should delete the parameter, if it exists. This is handled inside UrlSearchParams itself.
Now to actually update the url in the address bar, we use history.pushstate so the browser doesn’t have to reload.
const newRelativePathQuery = window.location.pathname + '?' + urlParams.toString();
history.pushState(null, '', newRelativePathQuery);
And the reason for newRelativePathQuery is if we passed urlParams directly, then it would “eat” into the url of the page, which would cause issues.
The completed code looks as follows for my use case
const addUserSearchUrlParameters = (q, pageIndex) => {
const urlParams = new URLSearchParams(window.location.search);
if(typeof q !== 'undefined' && q !== ''){
urlParams.set('search', q);
}else{
urlParams.delete('search');
}
if(typeof pageIndex !== 'undefined' && pageIndex > 0){
urlParams.set('page', pageIndex);
}else{
urlParams.delete('page');
}
const newRelativePathQuery = window.location.pathname + '?' + urlParams.toString();
history.pushState(null, '', newRelativePathQuery);
localStorage.setItem('last_visited_page', window.location.href);
}