@exabytellc/utils
Version:
EB react utils to make everything a little easier!
75 lines (71 loc) • 3.32 kB
JavaScript
import StorageHelper from "../_helpers/StorageHelper";
export default class UrlParams extends StorageHelper {
/**
* Get a parameter from the URL.
* @param {string} name - The name of the parameter to retrieve.
* @param {Object} options - Additional options.
* @param {boolean} [options.list=false] - Whether the parameter is expected to be a list.
* @param {string} [options.url=null] - The URL from which to retrieve the parameter.
* @returns {string|null} - The value of the parameter if found, otherwise null.
*/
static get(name, { list = false, url = null } = {}) {
return this.handleTryCatch({
n: "get",
k: name,
e: () => {
const uri = new URL(url ?? window.location.href);
const value = list ? uri.searchParams.getAll(name) : uri.searchParams.get(name);
return value;
}
});
}
/**
* Set a parameter in the URL.
* @param {string} name - The name of the parameter to set.
* @param {string|string[]} value - The value(s) of the parameter.
* @param {Object} options - Additional options.
* @param {boolean} [options.list=false] - Whether the parameter is expected to be a list.
* @param {string} [options.url=null] - The URL to which to set the parameter.
* @param {string} [options.state=null] - Replace current URL state with new URL, only if using current browser url
* @returns {string|null} - The modified URL with the updated parameters, or null if the operation failed.
*/
static set(name, value, { list = false, url = null, state = true } = {}) {
return this.handleTryCatch({
n: "set",
k: name,
f: false,
e: () => {
const uri = new URL(url ?? window.location.href);
if (list && Array.isArray(value)) {
uri.searchParams.delete(name);
for (let v of value) uri.searchParams.append(name, v);
} else {
uri.searchParams.set(name, value);
}
if (!url && state) window.history.replaceState({}, '', uri.toString());
return uri.toString();
}
});
}
/**
* Delete a parameter from the URL.
* @param {string} name - The name of the parameter to delete.
* @param {Object} options - Additional options.
* @param {string} [options.url=null] - The URL from which to delete the parameter.
* @param {string} [options.state=null] - Replace current URL state with new URL, only if using current browser url
* @returns {string|null} - The modified URL with the updated parameters, or null if the operation failed.
*/
static del(name, { url = null, state = true } = {}) {
return this.handleTryCatch({
n: "del",
k: name,
f: false,
e: () => {
const uri = new URL(url ?? window.location.href);
uri.searchParams.delete(name);
if (!url && state) window.history.replaceState({}, '', uri.toString());
return uri.toString();
}
});
}
}