toolbox icon indicating copy to clipboard operation
toolbox copied to clipboard

working with params and queries in the url

Open xGooddevilx opened this issue 1 year ago • 1 comments

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); // DATE

xGooddevilx avatar May 29 '24 10:05 xGooddevilx

Hey @gooddevil79, thanks for the proposal. I have a few comments on the current implementation:

  1. We should avoid using window in our functions as it couples the implementation to the browser, which we aim to avoid in the toolbox. This makes it difficult to test and renders the function unusable in other runtimes like Deno or Node.js. I suggest we get the search params from the parameters.

  2. There's a standard way of parsing search params using URLSearchParams, I strongly suggest using it, as all runtime supports and handles all cases (even for this implementation)

const getUrlParams = (search) => {
  const params = new URLSearchParams(search);
  const paramsObj = {};
  for (const [key, value] of params) {
    paramsObj[key] = isNaN(value) ? value : parseFloat(value);
  }
  return paramsObj;
};
  1. There are some uncovered cases, for instance, What happens if we have ?items[]=10&items[]=20? which is a valid query parameter and is usually used by some frameworks to represent arrays. this implementation overrides the latest one and ignores others.

  2. Implicit type conversion can also lead to unexpected behavior. Consider this example:

getUrlParams('?userId=0332103912&phone=09123456789&username=1e9');
// {userId: 332103912, phone: 9123456789, username: 1000000000}

This result is unintended and can lead to unpredictable behavior. It'd be safer to let developers explicitly decide how to parse the data.

ASafaeirad avatar Jul 03 '24 09:07 ASafaeirad