-1

I'm having a problem due to scope/hoisting/load order. In the following the Auth0Lock is defined inside the if block on line 6, but not immediately outside of it, or within the class. Does anyone know why??

import { EventEmitter } from 'events';
import { isTokenExpired } from './jwtHelper';

console.log('in');
const isClient = typeof window !== 'undefined';
if (isClient) {
  let Auth0Lock = require('auth0-lock').default;
  console.log('isClient');
  console.log('Auth0Lock inner', Auth0Lock);
}
  console.log('Auth0Lock outer', Auth0Lock);
export default class AuthService extends EventEmitter {
  constructor(clientId, domain) {
    super();
    console.log('happening');
    if (!isClient) {
      console.log('returning');
      return false;
    }
    // Configure Auth0
    this.lock = new Auth0Lock(clientId, domain, {});
    // Add callback for lock `authenticated` event
    this.lock.on('authenticated', this._doAuthentication.bind(this));
    // Add callback for lock `authorization_error` event
    this.lock.on('authorization_error', this._authorizationError.bind(this));
    // binds login functions to keep this context
    this.login = this.login.bind(this);
  }

 // curtailed
}
user1775718
  • 1,499
  • 2
  • 19
  • 32

2 Answers2

2

The let keyword is block scoped: https://developer.mozilla.org/nl/docs/Web/JavaScript/Reference/Statements/let

let x = "hey";
{ let x= "hi"; }

The outer let x is not being overwritten because it is in it's own scope. To come back at your question. Your let Auth0Lock exists only in the if block.

Michelangelo
  • 5,888
  • 5
  • 31
  • 50
1

The code tries to determine if it runs in a browser (typeof window === "object" in a browser), and if it does so, it tries to load the 'auth0-lock' module using some CommonJS style module loader.

There are two big problems with that:

If it is intended to run on nodejs side as well, the module will throw a TypeError: Auth0Lock is not defined on line 11, because it is not defined for real.

If it is running in the browser, it will still throw a TypeError, because the let keyword is block scoped, so in line 11 it is still not defined.

Tamas Hegedus
  • 28,755
  • 12
  • 63
  • 97