Skip to content

working with params and queries in the url #70

@xGooddevilx

Description

@xGooddevilx

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

Metadata

Metadata

Assignees

No one assigned

    Labels

    proposalNew feature or request

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions