Stack Exchange
URL query parameters returns null even when parameter is seted
I have a react app with react router and dynamic URL. And i also have 2 GET parameters like /?name=something&date=2021 and while name parameter works fine date for some reason always returns null.
I set parameters in form with onSubmit
function submitAction(e) {
  e.preventDefault();
  props.onChange(search, selectedDate);
  const currUrl = new URL(window.location.href);
  currUrl.searchParams.set("date", format(selectedDate, "yyyy"));
  currUrl.searchParams.set("name", search);
  window.history.pushState({}, "", currUrl);
  setSearch("");
}

And get parameters with useEffect() react hook
  useEffect(() => {
const params = new URLSearchParams(window.location.href);
const date = params.get("date");
const name = params.get("name");
console.log(name);
console.log(date);  //this always returns null
if (name) {
  setFilter(name);
}
if (date) {
  setDate(new Date(date));
}}, []);

So my query string changes and it works, but my second URL parameter isn't working
Query string looks like http%3A%2F%2Flocalhost%3A3000%2F%3Fdate=2018&name=

Put a console.log(selectedDate); in submitAction to test the value. Also, what is the code of the format function?

console.log(selectedDate) returns Date Tue Jun 05 2018 11:38:33 GMT+0300

format is a function from date-fns package that parse Date() object to needed format

What does console.log(format(selectedDate, 'yyyy')); output?

for Date Tue Jun 05 2018 11:38:33 GMT+0300 console.log(format(selectedDate, 'yyyy')) returns 2018

URL is changing but I still can't get date parameter after refreshing page. And name works just as intended. I don't understand why.
Right now my URL is http://localhost:3000/?date=2018&name= .And while console.log(name) in useEffect() returns empty string date returns null

The URLSearchParams constructor does not parse full URLs, only the query string portion. I suspect this is where the issue is.

In my case I need only query strings to set default state of search filter with url parameters. Other part of routing depends on react-router

The point is you are passing window.location.href, which is a full URL, in the URLSearchParams constructor. It doesn't parse full URLs, so this is likely what is causing your issue.

You can use window.location.search in the URLSearchParams constructor to get the correct details.

The URLSearchParams constructor does not parse a full URL, only the query string.
Change
const params = new URLSearchParams(window.location.href);

To
const params = new URLSearchParams(window.location.search);

