Nimila Hiranya
Nimila Hiranya

Reputation: 5192

Token received by RemotePushIOS cannot be set as a State

I'm using RemotePushIOS to get the Device Token.

RemotePushIOS.requestPermissions(function(err, data) {
    if (err) {
        console.log("Could not register for push");
    } else {
        console.log(data.token);
        var value = "v"+data.token;

        console.log("VALUE: " + value);
        this.setState({
            deviceToken: value
        });
    }
});

The console.log prints the token but when setting the state with the token, program crashes with the following error.

'undefined is not an object (evaluating 'this.setState')'

Why is this happening? What is the workaround?

Upvotes: 1

Views: 20

Answers (1)

jevakallio
jevakallio

Reputation: 35920

The issue is, that your this reference is not pointing to your component.

In order to avoid the this reference getting bound to the callback function, you can use an ES6 arrow function instead of the function keyword.

Replace

RemotePushIOS.requestPermissions(function(err, data) {

With

RemotePushIOS.requestPermissions((err, data) => {

ES6 arrow functions are lexically scoped, so the this inside the function will point to the context outside the function, which, assuming you are executing this code inside a method of you component, will be referring to your component.

Upvotes: 2

Related Questions