URLSearchParams returns empty object

Viewed 6002

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 {}
}
5 Answers

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.

Turns out when you do this in the chrome dev console it returns an empty object to the console instead of the standard way it shows an object with multiple keys

params = new URLSearchParams(window.location.search)

You would expect it show an object with keys when you log out params but it does not. In order to actually see them in the console you need to iterate through it with a loop

for (let item of params) {
  console.log('item: ', item)
}

Pretty confusing since I was expected it to work like a normal object

I guess that you use react-router and append URL query string to /buildings. So this.props.location.search is empty.

history.push({
  pathname: '/buildings?search_query=test&page=2',
});

Please set up URL query string in search property.

history.push({
  pathname: '/buildings',
  search: '?search_query=test&page=2'
});

URLSearchParams are iterable, so you can also do [...params] to get an array of key-value pairs.

Related