Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

`this` is null in instantiated class in Saga file #1389

Closed
fillippeyton opened this issue Apr 10, 2018 · 2 comments

Comments

@fillippeyton
Copy link

commented Apr 10, 2018

I'm having an issue with an API service I've created as an ES6 class, but it seems to lose its reference to this. I created this class to make api calls, and imported it into my Saga file.

I created this test playground (forked from another codesandbox; repurposed for my test). My code is simplified to isolate the issue. When I have redux-saga run call of api.post, this is null for some reason.

Here's my code:

import { put, call, takeEvery } from "redux-saga/effects";

export function* incrementAsync() {
  const response = yield call(api.post, "/login");

  console.log("ApiService response");
  yield console.log(response);

  yield put({ type: "INCREMENT" });
}

export default function* rootSaga() {
  yield takeEvery("INCREMENT_ASYNC", incrementAsync);
}

class ApiService {
  constructor(token) {
    this.token = token || null;
  }

  post(path) {
    // `this` is null
    console.log("ApiService `this`");
    console.log(this);
    return this.token + path;
  }
}

const api = new ApiService("1e21fFv3v13v1gv3.tv13v");

I did a test to ensure that generator functions didn't have an issue with using class instances and everything seemed to work fine: https://jsfiddle.net/76khLybx/

I'm not really sure why this is happening, and I'm contemplating re-writing my ApiService class into a function instead, but is there a reason why the instance is losing reference to this within the method call?

@MichelSimonot

This comment has been minimized.

Copy link

commented Apr 10, 2018

Have you tried using call([context, fn/fnName], ...args)?

I don't remember the details, but I've run into a similar problem. I believe this is expected/known, which is what the call([context, fn/fnName], ...) effects should help with.

@fillippeyton

This comment has been minimized.

Copy link
Author

commented Apr 10, 2018

That seemed to fix the issue. Kinda strange that I didn't find anything in my searching, pointing to special treatment for an instantiated class. Appreciate the reply! I'll close this issue.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Projects
None yet
2 participants
You can’t perform that action at this time.