'Next React - ReferenceError: window is not defined [duplicate]
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?
Solution 1:[1]
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) {...}
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | teo-garcia |
