1

I have two reusable functions where I use window.localStorage.getItem method.

const userByToken = () => {
    const dispatch = useDispatch();
    const token = window.localStorage.getItem("token");
    const refreshToken = window.localStorage.getItem("refreshToken");
}

this function returns error for using window

but second function

    const useValidateToken = (setLoadingState: any) => {
      const router = useRouter();
      useEffect(() => {
          const token = window.localStorage.getItem("token");
          const refreshToken = window.localStorage.getItem("refreshToken");
      })
    }

doesn't return error.

why do I get error without useEffect?

1
  • 1
    In addition to the linked resolution - the why is most likely because server-side NextJS only performs the first render, so useEffects are not called. But your first snippet is not in an effect, so it tries to call it during the server-side rendering Commented Jan 31, 2022 at 17:52

1 Answer 1

3

Next pre-renders components firstly in the server, where the window object does not exist.

You have to use useEffect or add kind of guards to avoid crashing when running the first render

  const isBrowser = !!window; // Feel free to define which is the best way to detect when is being runner in the browser
  if (isBrowser) {...}
Sign up to request clarification or add additional context in comments.

4 Comments

Thank you for your respond, so it's not possible to use window without useEffect
You should use typeof window !== 'undefined' check. Calling !!window will raise ReferenceError on server-side.
You right @Aitwar, my demonstration was vague
Hi, this answer is wrong, you need the guard to be wrapped into an effect. See the other question in the duplicate notice.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.