javascriptreactjsurlparseurl-parsing

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


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?


Solution

  • 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