0

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?

juliomalves
  • 42,130
  • 20
  • 150
  • 146
  • 1
    In addition to the linked resolution - the *why* is most likely because server-side NextJS only performs the first render, so `useEffect`s are not called. But your first snippet is not in an effect, so it tries to call it during the server-side rendering – Brian Thompson Jan 31 '22 at 17:52

1 Answers1

4

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) {...}
teo-garcia
  • 111
  • 3