Flux(Alt): ReferenceError: localStorage is not defined

2.1k views Asked by At

I'm trying to store session data to the localStorage but I receive an error. "ReferenceError: localStorage is not defined"

Here is the code.

import alt from '../alt';
import UserActions from '../actions/UserActions.js';

// To Do: Inplement LocalStorage Polyfill

class UserStore {
  constructor() {
    this.initialize();
    this.bindListeners({
      onLoginSucceeded: UserActions.LOGIN_SUCCEEDED
    });
  }
  initialize() {
    this.setState({
      // There's an error here.
      _loggedIn: localStorage.getItem('loggedIn'),
      _authToken: localStorage.getItem('authToken'),
      _userId: localStorage.getItem('userId'),
      _profile: localStorage.getItem('profile')
    });
  }
  onLoginSucceeded(data) {
    this.setState({
      _loggedIn: true,
      _authToken: data.authToken,
      _userId: data.userId,
      _profile: data.profile,
      _user: data.user
    });
    // There's no error here.
    localStorage.setItem('authToken', data.authToken);
    localStorage.setItem('loggedIn', data.loggedIn);
    localStorage.setItem('userId', data.userId);
    localStorage.setItem('profile', data.profile);
  }

  getCurrentUser() {
    return this.state._user;
  }

  isLoggedIn() {

  }

}

export default alt.createStore(UserStore, 'UserStore');

I'm new to es6, so I may miss something, but I couldn't find anything like I cannot call global object inside class. It is helpful if you have any idea about this error.

[Edit] This works in the es6fiddle http://www.es6fiddle.net/ichmbt0e/

class UserStore {
  constructor() {
    this.initialize();
  }

  initialize() {
    this.setState({
      _loggedIn: localStorage.getItem('loggedIn'),
      _authToken: localStorage.getItem('authToken'),
      _userId: localStorage.getItem('userId'),
      _profile: localStorage.getItem('profile')
    });
  }

  isLoggedIn() {

  }

}
1

There are 1 answers

1
Atsuhiro Teshima On BEST ANSWER

I found out that I need to use Alt.bootstrap when retrieve data from localStorage.

// client.js

import 'es6-shim';
import 'whatwg-fetch';
import Iso from 'iso';
import Router from 'react-router';
import React from 'react';
import routes from './client/routes';
import alt from './client/alt';

Iso.bootstrap(function(state, _, container) {
  var userStoreData = {
    UserStore: {
      _loggedIn: localStorage.getItem('loggedIn'),
      _authToken: localStorage.getItem('authToken'),
      _userId: localStorage.getItem('userId'),
      _profile: localStorage.getItem('profile')
    }
  }
  var new_state = Object.assign(JSON.parse(state), userStoreData)
  alt.bootstrap(JSON.stringify(new_state));

  Router.run(routes, Router.HistoryLocation, function(Handler) {
    var node = React.createElement(Handler);
    React.render(node, container);
  });
});