iamsaksham
iamsaksham

Reputation: 2949

Redux React: Not able to access 'this' inside a function of another class

I have a class named iccSdk which have a function with the name on. Now inside my React's render, i am calling the function iccSdk.on(). Further I want to dispatch an action from within this function so I try to use this.props.actions.chatConnect(data); but this is becoming undefined here.

1st attempt:

render() {
    console.log(this);
    iccSdk.on('connect', function(data) {
      console.log(this);
      this.props.actions.chatConnect(data);
    });
...
}

In above case this is shown as undefined inside the function but it looks good outside my iccSdk.on() function.

2nd attempt:

render() {
    var t = this;
    iccSdk.on('connect', function(data) {
      t.props.actions.chatConnect(data);
    });
...
}

In the 2nd attempt it works fine but I doubt is it a good practice to do so, and i am also confused why this is not accessible inside my iccSdk.on()

Upvotes: 0

Views: 469

Answers (2)

Lalli Nuorteva
Lalli Nuorteva

Reputation: 163

Function creates a new scope. Therefore the context (=this) is different or does not exist. Your second approach is fine.

Other ways to do this:

Arrow function:

Arrow function does not create a new context for the function. Therefore you can use the same this inside your function. For this ES6 is required.

render() {
    console.log(this);
    iccSdk.on('connect', data => {
      console.log(this);
      this.props.actions.chatConnect(data);
    });
...
}

Bind

With bind function you can bind "this" to your function.

render() {
    console.log(this);
    iccSdk.on('connect', function(data) {
      console.log(this);
      this.props.actions.chatConnect(data);
    }.bind(this));
...
}

thisArg

iccSdk.on might also take "this argument". I'm not sure if it does. You can read more about thisArg here: https://h3manth.com/new/blog/2014/thisarg-in-javascript/

Upvotes: 4

sehrob
sehrob

Reputation: 1044

This is a reference to an object which is given to a method. In a method you can access the given object and it is This. But on method is of iccSdkso, it can't access other objects by this variable. Every method can only access its own object.

So, if you want to access another object in a method, you can use your second attempt (it is normal I guess), or you can bind the method to the object you want to access like this:

function () {
    console.log(this)
}.bind(this)

Upvotes: 1

Related Questions