How to avoid getting error 'localStorage is not defined' on server in ReactJS isomorphic app?

二次信任 提交于 2020-06-06 06:17:48

问题


I was using localStorage in my webApp to store data on client side. But when I've tried to make the app isomorphic, this causes an issue. Due to node is not browser environment, it can't define such objects as 'window', 'localStorage' etc. How do I solve this issue?


回答1:


You could use a check whether the code is being executed on the server or on the client side by checking whether module is not 'undefined':

var isNode = typeof module !== 'undefined'

You can then proceed to only executed this code on the client side:

if(!isNode){
   //use the local storage
   var myItem = localStorage.getItem(itemTitle)
}

However, you should already always check whether Storage is defined before using since not all browsers support it:

if(typeof(Storage) !== "undefined"){
   //use the local storage
}



回答2:


Standard has specific support for problems like this.

All you need to do is add a comment informing standard that there is a variable provided by the global scope.

// MyStuff.js
/* global localStorage */

// Use localStorage below with no linter errors


来源:https://stackoverflow.com/questions/33724396/how-to-avoid-getting-error-localstorage-is-not-defined-on-server-in-reactjs-is

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!