Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ReferenceError: localStorage is not defined in ReactJS Build

I am using localStorage a lot on my authenticated components in my react application to get user details from local storage as well as storing them on login.

When I build my app, it throws ReferenceError: localStorage is not defined.

I know this could be because node does not have access to localStorage and thus the error.

How can I solve the problem?

Here is an example of code I use in my component.

import React, {PropTypes} from 'react';
import AccountBasicInfo from '../components/AccountBasicInfo';


export class Account extends React.Component {


    userBasicInfo(){
      const user = localStorage.getItem('User') ? JSON.parse(localStorage.getItem('User')) :{};
      const cashback = localStorage.getItem('cashback') ? JSON.parse(localStorage.getItem('cashback')) :{};
    }
    render(){
      return(
          <div>
              <AccountBasicInfo theme="theme2" item={this.userBasicInfo.bind(this)()}/>
          </div>
      );
    }
}



export default Account;
like image 917
Harsh Maur Avatar asked Aug 10 '16 15:08

Harsh Maur


People also ask

Can I use localStorage in Nextjs?

If you're used to working with client-only applications, it may come as a surprise that you can't access localStorage from the server. This is because localStorage is not defined on the window object, and Next. js performs a server render before the client render.

How do you define local storage?

What is localStorage in JavaScript? localStorage is a property that allows JavaScript sites and apps to save key-value pairs in a web browser with no expiration date. This means the data stored in the browser will persist even after the browser window is closed.


1 Answers

If you need to run the same, unmodified code on node, which does not have a native localStorage implementation, you could consider using a shim such as node-localstorage.

You could also consider rewriting your code to use an alternative means of storing information.

like image 86
TW80000 Avatar answered Oct 12 '22 23:10

TW80000