How can I parse the query in url in react js using url-parse package?

10.5k Views Asked by At

I want to parse the query in the url in react js like this :

 const location = useHistory().location;
 const parsed = parse(location, true);
 console.log(parsed);

But the console gives me this :

host: "localhost:3000"
hostname: "localhost"
href: "http://localhost:3000/[object Object]"
origin: "http://localhost:3000"
password: ""
pathname: "/[object Object]"
port: "3000"
protocol: "http:"
query: {}
slashes: true

The query object is empty which I need that one and the pathname is not useable . How can I parse the query in url in react js using url-parse package properly?

2

There are 2 best solutions below

0
On BEST ANSWER

Fixed the problem by using the query-string package.

import queryString from 'query-string';

const location = useHistory().location;
const query = queryString.parse(location.search); // returns the query object
0
On

I think you are using the wrong react hooks. useHistory hook is used for programmatic navigation purposes. For accessing location object use useLocation.

import { useLocation } from 'react-router-dom';

const location = useLocation();
const parsed = parse(location.search, true);