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

后端 未结 2 878
面向向阳花
面向向阳花 2020-12-10 04:01

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 environ

相关标签:
2条回答
  • 2020-12-10 04:28

    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
    }
    
    0 讨论(0)
  • 2020-12-10 04:43

    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
    
    0 讨论(0)
提交回复
热议问题