-
Notifications
You must be signed in to change notification settings - Fork 18
Open
Labels
proposalNew feature or requestNew feature or request
Description
Function Signature
const getUrlParams = () => {
const pl = /\+/g;
const search = /([^&=]+)=?([^&]*)/g;
const decode = (s) => {
return decodeURIComponent(s.replace(pl, " "));
};
const query = window.location.search.substring(1);
const urlParams = {};
let match;
while ((match = search.exec(query))) urlParams[decode(match[1])] = decode(match[2]);
Object.keys(urlParams).map((keyName) => {
if (!isNaN(urlParams[keyName])) urlParams[keyName] = parseFloat(urlParams[keyName]);
});
return urlParams;
};Motivation
we typically use useSearchParams in nextjs ( or other related hooks in react ), in order to get a query from the url, it's ok , but you need to be specific which query you are looking for and pass it as string to searchParams.get("name").
by using this function (getUrlParams) , we can get all queries in the url at a time. and destructor the one we need.
as an example :
imagine we have this url
sample.com/page?test=idk&orderBy=DATE
and need to get orderBy query, we simply do this :
const {orderBy} = getUrlParams(); // it return all queries {test:"idk",orderBy:"DATE"}
console.log(orderBy); // DATEMetadata
Metadata
Assignees
Labels
proposalNew feature or requestNew feature or request