Home > database >  react-URLSearchParams returning Null object
react-URLSearchParams returning Null object

Time:12-25

I am using the following code to retrieve query parameters from URL but URLSearchParams returns an empty object. p.s uselocation.search returning correct output.

const stringdata = useLocation().search

  const queeryparameter = new URLSearchParams(stringdata)
    
      console.log("queeryparameter :", queeryparameter)
    
    
      const query = queeryparameter.get('q');
    

      var url_string = `http://localhost:3000/recipes${query}`

CodePudding user response:

Try to use useParams from react-router.

​const​ query​​ ​=​ ​useParams​(​)​;

Don't forget to import, ​import​ ​{​ ​useParams​ ​}​ ​from​ ​"react-router-dom"​;

CodePudding user response:

You can try using window.location.search over user search params. That should look something like:

const queryParams = new URLSearchParams(window.location.search);
const query = queryParams.get('q');
let url_string = `http://localhost:3000/recipes${query}`;
        
  • Related