Using Object.keys() to get searchParams

Viewed 35

Considering the below:

const [searchParams, setSearchParams] = useSearchParams();

  console.log(searchParams.toString());

  console.log(typeof searchParams);

  console.log(Object.values(searchParams));

And passing the URL http://localhost:3000/client-data?task=test

This logs:

task=test (The string of the object, understandable)

object (We know it's of type object, and has some key value pairs from prior test)

[] (Why are we not getting any keys / values from Object.keys() etc?)

1 Answers

Why are we not getting any keys / values from Object.keys() etc?

The key/values of the search params are not exposed as own properties of the object instance. They cannot be. Consider the following

const params = new URLSearchParams("a=1&get=2");

console.log(params.a);
console.log(params.get);

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

If params.a gave you the value "1", then params.get should also give you "2". Yet that means it would overwrite the .get() method. And if that were to happen, then params.get("a") would never work.

Related