The background

Recently, BECAUSE I need to write a new project, I picked up the react-router-dom library, but when I searched the whole document, I found that there is no query parsing function. The only edge erasable is useLocation API, but this returns the search string. Not a Query, so parsing will have to be done yourself…

The body of the

In the spirit of being an engineer at Nocode, I immediately went to Github to search the relevant library and QS was a perfect match

— — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — line — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — —

Normal development would probably end at this point, but since this scenario happens so frequently (almost every project will need to parse URL Query), I decided to explore if there was a better solution.

It turns out that it does exist: URLSearchParams

Usage:

const querystring = '? Template =1' // parse const query = new URLSearchParams(queryString); Query. Get ('template');Copy the code

In addition to parsing URL queries, URLSearchParams has another big use case – serializing query objects to query strings on urls as follows:

const query = new URLSearchParams(); // Add the value query.append('template', 1); // Get the serialized query string query.toString(); // "template=1"Copy the code

One more step

The front-end has fully entered the TS era and can greatly improve the development experience through type inference. There is a small problem with the query returned above,query.get('xxx')The parameter can be filled in any string. Typo is easy to occur in development and not easy to maintain later. We want query.get() to tell us what arguments are available and to report a compilation error if an invalid argument is encountered:

Directly on the code:

function parseQuery<T extends Record<string, any>, K = keyof T>(queryStr: string) { const query = new URLSearchParams(queryStr); return { get(name: K) { // @ts-ignore return query.get(name); } } } interface Query { template: string; } const query = parseQuery<Query>('template=1'); query.get('template'); Query. / /) get (" id "); / / *Copy the code

conclusion

1. Query parsing can be performed directly using URLSearchParams

2. Make a layer of type encapsulation based on TS, improve development experience and reduce maintenance cost