mlegenhausen / fetch-intercept

Interceptor library for the native fetch command inspired by angular http intercepts.
MIT License
406 stars 52 forks source link

TypeError: Cannot read property '_instance' of undefined #26

Closed Harmonickey closed 6 years ago

Harmonickey commented 6 years ago

When I use the new Promise option for 'request' I get this error

Short TypeError: Cannot read property '_instance' of undefined

Stacktrace location

TypeError: Cannot read property '_instance' of undefined
    at register (index.js:130)

index.js line 130

/**
    * Register intercept hooks & return an interceptor instance
    * @param {object} hooks - The intercept hooks
    * @return {FetchInterceptor} An interceptor object
    */
    value: function register() {
      var hooks = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {};

      if (this._instance) {   // <<<<----- HERE IS LINE 130 of index.js
        return this._instance;
      }
      var interceptor = new this();
      for (var i = 0; i < this.hooks.length; i++) {
        var hook = this.hooks[i];
        if (typeof hooks[hook] === 'function') {
          interceptor[hook] = hooks[hook];
        }
      }
      interceptor.hijack();
      this._instance = interceptor;
      return interceptor;
    }

Here is how I setup my fetchInterceptor register call

fetchInterceptor.register({
      request: (url, config) => {
        return this.claimsService.getTokenForUser()
          .then(token => {
            config.headers['Authorization'] = token ? `Bearer: ${token}` : null;
            return [url, config];
          });
      },
      requestError: function (error) {
          return Promise.reject(error);
      },
      response: function (response) {
          return response;
      },
      responseError: function (error) {
          return Promise.reject(error);
      }
    });

The getTokenForUser() call is a Promise.

Maybe the switch to use Promise on the request method needs to take a closer look?

Harmonickey commented 6 years ago

Complete and utter mistake on my part, I imported the fetch-interceptor library, not the fetch-intercept library. You library works well, thanks.