javascriptreactjstypescriptreact-router

URLSearchParams returns empty object


I want to get search params and add params to URL, but getting empty array every time.

Example url - http://localhost:3000/buildings?search_query=test&page=2

constructor(props) {
  super(props);
  const params: URLSearchParams = new URLSearchParams(this.props.location.search);
  console.log(params); //Getting empty object {}
}

Solution

  • try

     console.log(params.get("page"));
    

    It should return '2'. The URLSearchParams is displayed as an empty object in the console and does not display all the values. It does allow you to call a get function though.

    Otherwise make sure the this.props.location.search does have an valid function.

    new URL("http://localhost:3000/buildings?search_query=test&page=2").search
    

    Does return a valid value for example.