Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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 {}
}
like image 722
kunwar11 Avatar asked May 08 '26 20:05

kunwar11


2 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.

like image 161
Peter Van de Laar Avatar answered May 11 '26 10:05

Peter Van de Laar


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

like image 28
Jose Avatar answered May 11 '26 10:05

Jose



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!