window is not defined #47028
Replies: 4 comments 2 replies
-
I have the same error. But I added "use client" in the top file. But not working yet.
window is not defined. |
Beta Was this translation helpful? Give feedback.
-
The problem is how JS expressions are executed, as you declare them, for example in: const isBrowser = () => typeof window !== "undefined";
const LS_favoriteList = JSON.parse(window.localStorage.getItem("favorite") || "[]");
const initialState: IState = {
favorites: isBrowser() && LS_favoriteList ? LS_favoriteList : []
}; You are defining, in the second line, an expression, and that means that it is evaluated as you declare it, much like saying: let x = 2 + 2 That'd make 4, so even though you are checking for Change it to: const isBrowser = () => typeof window !== "undefined";
const LS_favoriteList = () => { /* Do your reading the localstorage with fallbacks here */ }
const initialState: IState = {
favorites: isBrowser() ? LS_favoriteList() : []
}; |
Beta Was this translation helpful? Give feedback.
-
Client components are rendered on the server too. These so called "client components" are the same as, the components found in any React app up to these days. That means that components, including pages, within the pages directory also behave this way. I don't understand how changes from appDir to pages, could've had any impact in your problem, though I haven't really read through your example. Are you sure it wasn't something else that fixed it? Like |
Beta Was this translation helpful? Give feedback.
-
ran into the same error and am struggling to solve it for a long. |
Beta Was this translation helpful? Give feedback.
-
Summary
Hi guys! Searched a lot about this problem and the most common fix was to add
typeof window !== "undefined"
, but for some reason it didn't help me. The problem is in redux toolkit slice file. Also I don't know why but the error displays mostly when url is wrong and page not found. Here is example of my code:Additional information
No response
Example
No response
Beta Was this translation helpful? Give feedback.
All reactions