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?

1
  • 1
    Can this help? Commented Aug 29, 2020 at 13:24

2 Answers 2

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
Sign up to request clarification or add additional context in comments.

Comments

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);

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.