localstorage in redux & next js 13
Answered
Stony gall posted this in #help-forum
Stony gallOP
it works in development with showing the error in the screenshot ,
my app crush in production build time during to same error "[ ] - info Generating static pages (0/24)ReferenceError: localStorage is not defined
" .
i tried try{}catch{} / if(window) but it didn't help . any tips to fix this... or at least a way to force the build ?
my app crush in production build time during to same error "[ ] - info Generating static pages (0/24)ReferenceError: localStorage is not defined
" .
i tried try{}catch{} / if(window) but it didn't help . any tips to fix this... or at least a way to force the build ?
Answered by fuma
That’s simple, because your initial UI is rendered on the server, but your server isn’t able to access local storage. It’s impossible to remove the flash, but you can handle it by adding some skeletons on your UI.
7 Replies
You shouldn't use
localStorage outside of a useEffect hook, since client components are also pre-rendered on the server.You can set the default value of redux store in a
useEffect instead@fuma You can set the default value of redux store in a `useEffect` instead
Stony gallOP
i tried to do that in the route layout, but the route layout itself isn't wrapped in <Provider>
Do that in a client component under the Provider
Stony gallOP
i did it this way , there is no error now but i still must give it a fixed initial value in /reduc/slices/foo.js , also there is an initial glitch in my UI (it depends on a global state)
That’s simple, because your initial UI is rendered on the server, but your server isn’t able to access local storage. It’s impossible to remove the flash, but you can handle it by adding some skeletons on your UI.
Answer
Hence, the actual UI is only rendered after loading the value from local storage