1

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?

Mehdi Faraji
  • 2,574
  • 8
  • 28
  • 76

2 Answers2

3

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
Mehdi Faraji
  • 2,574
  • 8
  • 28
  • 76
2

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);
Artur A
  • 7,115
  • 57
  • 60