lmaccherone/node-localstorage

ReferenceError: localStorage is not defined

francisrod01 opened this issue · 4 comments

After implement the README usage, I see it on the console

ReferenceError: localStorage is not defined
      at testLocalstorage ...

I'm using this environments:

  • npm: 6.4.1
  • node: v8.11.2
  • react: ^16.4.2
  • node-localstorage: ^1.3.1

My implementation for it is below:

import { takeLatest, put } from 'redux-saga/effects';

import ActionCreators, { Types } from '../actionCreators';


const testLocalstorage = () => {
  if (typeof localStorage === "undefined" || localStorage === null) {
    const LocalStorage = require('node-localstorage').LocalStorage;
    localStorage = new LocalStorage('./scratch');
  }

  localStorage.setItem('myFirstKey', 'myFirstValue');
  console.log(localStorage.getItem('myFirstKey'));
}

testLocalstorage();

export function* checkUserSession() {
  const isUser = localStorage.getItem('isUser');
  const parseUser = JSON.parse(isUser);

  yield put(ActionCreators.checkUserSessionSuccess(parseUser));
}


export default function* sessionWatcher() {
  yield takeLatest(Types.CHECK_USER_SESSION_REQUEST, checkUserSession);
}

Try adding a let, const, or var so you'd have let localStorage = new LocalStorage('./scratch');

It's not make effect.

const testLocalstorage = () => {
  if (typeof localStorage === "undefined" || localStorage === null) {
    const LocalStorage = require('node-localstorage').LocalStorage;
    let localStorage = new LocalStorage('./scratch');
  }

  localStorage.setItem('myFirstKey', 'myFirstValue');
  console.log(localStorage.getItem('myFirstKey'));
}

testLocalstorage();

@francisrod01 I don't know if you have figured it out or not but you are declaring localstorage inside if scope and using it outside that scope where its not available.

For tests, I made some adjustments and a check if isUser is empty or not and then I'm using now jest.fn.

For SSR (server-side rendering) I have the same problem.
I'll try to use node-localstorage.

@lmaccherone I think it should be possible to create the store one time and use it in entire application as a provider.