filmov
tv
How to Solve ReferenceError: localStorage is not defined in Next.js

Показать описание
---
If anything seems off to you, please feel free to write me at vlogize [AT] gmail [DOT] com.
---
Understanding the Problem
Key Points
Window Object: The localStorage belongs to the window object, which is not defined on the server.
React Hooks: React's useEffect hook runs only after the component has mounted, allowing you to safely access client-only resources like localStorage.
Solution: Checking for window Object
To resolve the error, you can conditionally access localStorage only when the code is running in the browser. Here's how you can achieve that:
Step-by-Step Implementation
Modify the Initial State: Update the way you initialize values that rely on localStorage. You can achieve this using a conditional check, as shown in the following code snippet:
[[See Video to Reveal this Text or Code Snippet]]
Explanation of the Code
typeof window !== "undefined": This checks whether the code is running in the browser (where window is defined). If it’s undefined, the code is executing on the server.
Fallback Values: When running on the server, we return null for access and refresh to avoid any runtime errors.
Example Usage in Your Redux Reducer
You will typically implement this adjustment in the Redux reducer where you initialize the state. The altered initialState would look something like this:
[[See Video to Reveal this Text or Code Snippet]]
Conclusion
If anything seems off to you, please feel free to write me at vlogize [AT] gmail [DOT] com.
---
Understanding the Problem
Key Points
Window Object: The localStorage belongs to the window object, which is not defined on the server.
React Hooks: React's useEffect hook runs only after the component has mounted, allowing you to safely access client-only resources like localStorage.
Solution: Checking for window Object
To resolve the error, you can conditionally access localStorage only when the code is running in the browser. Here's how you can achieve that:
Step-by-Step Implementation
Modify the Initial State: Update the way you initialize values that rely on localStorage. You can achieve this using a conditional check, as shown in the following code snippet:
[[See Video to Reveal this Text or Code Snippet]]
Explanation of the Code
typeof window !== "undefined": This checks whether the code is running in the browser (where window is defined). If it’s undefined, the code is executing on the server.
Fallback Values: When running on the server, we return null for access and refresh to avoid any runtime errors.
Example Usage in Your Redux Reducer
You will typically implement this adjustment in the Redux reducer where you initialize the state. The altered initialState would look something like this:
[[See Video to Reveal this Text or Code Snippet]]
Conclusion