K
K
kamelot432020-12-24 12:07:53
JavaScript
kamelot43, 2020-12-24 12:07:53

How to take values ​​from the address bar in React and send a request?

Guys, good afternoon. React app in development. There are search pages with different filters. When passing data to the address bar of the browser and going to the page, search filters should be applied, a request should be sent to the server and the data should be drawn on the page according to the selected filters. What could be the approach to accomplish this task?
Before loading the page, we check if there are parameters after the '?' sign, if yes, then we parse this line, form an object with a request, send a request using the axios method to receive data ? while there is such an idea, but such an algorithm seems complicated to me, especially the stage of breaking the string and forming an object from it for the axios request. please tell me there is a more elegant solution to this case or similar examples where you can peep something? thanks in advance.

5fe45a63cc660120564536.png

Answer the question

In order to leave comments, you need to log in

2 answer(s)
A
Andrey Dyrkov, 2020-12-24
@VIKINGVyksa

Hello, use the URL constructor, it will break your url into its component parts, this will make it easier for you to work with the address.

var url = new URL('https://hello.com?name=alex'); // or document.location
url.searchParams.get('name') // ~> alex

K
Kirill Mager, 2020-12-24
@magerrrr

Query-string was created to make it easier to work with the address bar of all browsers.
Usage:

const queryString = require('query-string');
 
queryString.parseUrl('https://foo.bar?foo=bar');
//=> {url: 'https://foo.bar', query: {foo: 'bar'}}
 
queryString.parseUrl('https://foo.bar?foo=bar#xyz', {parseFragmentIdentifier: true});
//=> {url: 'https://foo.bar', query: {foo: 'bar'}, fragmentIdentifier: 'xyz'}

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question