Skip to content

Instantly share code, notes, and snippets.

@erkobridee
Last active December 12, 2024 08:19
Show Gist options
  • Save erkobridee/d0aa43b42289411f3070463f745f1d79 to your computer and use it in GitHub Desktop.
Save erkobridee/d0aa43b42289411f3070463f745f1d79 to your computer and use it in GitHub Desktop.
export const removeQueryParam = (key: string) => {
const existingValue = getFromQuery(key)
if (existingValue === null) {
return;
}
const url = new URL(window.location as any);
url.searchParams.delete(key);
history.pushState({}, '', url);
}
/**
* it provides support to retrieve an array of data
*
* @example
* ```
* // url = `?sort=a&sort=b`
*
* getFromQuery('sort')
*
* // ['a', 'b']
* ```
*/
export const getFromQuery = <R = string>(key: string): R | null => {
const urlSearchParams = new URLSearchParams(window.location.search);
if(!urlSearchParams.has(key)) {
return null;
}
const values = urlSearchParams.getAll(key);
return (values.length > 1 ? values : values[0]) as R;
}
/**
* handle multiple query parameters with support to array of data
*
* @param {Record<string, any>} params - object to be converted into `URLSearchParams`
*
* @example
* ```
* params = {
* attr1: 'value1',
* sort: ['a', 'b']
* }
*
* // `attr1=value1&sort=a&sort=b`
* ```
*/
export const toQueryParams = (
params: Record<string, any>
): URLSearchParams => {
const urlSearchParams = new URLSearchParams();
for(const [key, value] of Object.entries(params)) {
if(Array.isArray(value)) {
// remove any falsy value
value.filter(Boolean).forEach(item => {
urlSearchParams.append(key, String(item));
});
} else {
let valueToUse: string | undefined = undefined;
switch(Object.prototype.toString.call(value)) {
case '[object Date]':
valueToUse = new Date(value).toISOString();
break;
case '[object Boolean]':
case '[object Number]':
case '[object String]':
valueToUse = String(value);
break;
}
valueToUse && urlSearchParams.set(key, valueToUse);
}
}
return urlSearchParams;
}
/** support to set multiple query parameters on the URL */
export const setQueryParams = (params: Record<string, any>) => {
const url = new URL(window.location as any);
url.search = toQueryParams(params).toString();
history.pushState({}, '', url);
}
/** support to retrieve multiple query parameters from the URL */
export const fromQueryParams = (): Record<string, any> => {
const urlSearchParams = new URLSearchParams(window.location.search);
const params: Record<string, any> = {};
for(const key of urlSearchParams.keys()) {
params[key] = getFromQuery<string | string[]>(key)!;
}
return params;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment