0

I have logged out the following window.location in my React app (using Google Chrome):

{
    "ancestorOrigins": {},
    "href": "http://localhost:3000/my-path?foo=bar",
    "origin": "http://localhost:3000",
    "protocol": "http:",
    "host": "localhost:3000",
    "hostname": "localhost",
    "port": "3000",
    "pathname": "/my-path",
    "search": "?foo=bar",
    "hash": ""
}

However, logging out window.location.search in the console (on the next line) shows that it's an empty string: "". This seems to contradict the search field on the window.location object. Here are my logs:

console.log("location", window.location); // search: "?foo=bar"
console.log("search", window.location.search); // ""

Furthermore, both (a) a simple 1 second timeout inside a React.useEffect and (b) a page reload each result in the window.location.search logging out to be "?foo=bar" as expected.

I expected window.location.search to match the search field on the window.location object, but it doesn't. I suspect some sort of race condition, but I don't understand the mismatch between window.location and window.location.search

  • 2
    You’re probably not seeing window.location as it was when the console.log command ran. See https://stackoverflow.com/questions/23392111/console-log-async-or-sync – James Mar 17 '23 at 19:08

1 Answers1

0

As @james pointed out in the comments, it turns out that my first console.log was referencing the stored window.location object, which initially had an empty search field, but later was updated with a populated search field. The log in the dev tools UI was simply updated to reflect this change.

This is corroborated by another log I added as a test:

// includes `"search":""`
console.log("stringified", JSON.stringify(window.location));

See this post for more details.