0
votes

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
Does this answer your question? Window is not defined in Next.js React appWill Jenkins
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 renderingBrian Thompson

1 Answers

1
votes

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) {...}