D
D
djEban2022-03-25 15:17:08
JavaScript
djEban, 2022-03-25 15:17:08

Is there any difference in how to check if window exists in js?

I'm starting the NextJS project. The code is first executed on the server, hence there is no window.

const [isMobile, setIsMobile] = useState(window?.innerWidth < 1000);


But during the build swears. that window is undefined. although I explicitly indicated optional chaining
. Is it connected, perhaps, with the fact that the code is translated into es5 syntax? It's just that if you put typeof window !== undefined, then everything works

Answer the question

In order to leave comments, you need to log in

1 answer(s)
W
wonderingpeanut, 2022-03-25
@djEban

This is due to the fact that the html document is generated on the server. As you yourself said, there is no window object on the server, which is why it swears.
Do It

const [isMobile, setIsMobile] = useState(undefined);

and when loading the page, change the state to the value you need (useeffect)
const [state,setState] = useState();
useEffect(() => {
  if (typeof window !== 'undefined')
    setState(...)
}

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question