xoomer
xoomer

Reputation: 321

ReactJS : this.setState is not a function?

I am new to ReactJS and I am having an error "this.setState is not a function".

constructor() {
    super();

    this.state = {
        visible: false,
        navLinesShow: true
    };

    this.navOpen = this.navOpen.bind(this)

}

navOpen() {
    this.setState({
        navStatus: "navShow",
        navLinesShow: false
    });

    if ( this.state.visible === false) {

        setTimeout(function (){

            this.setState({
                visible: true
             });

        }, 3000);

    }

I have added this.navOpen = this.navOpen.bind(this) to the contructor. So I guess the problem is with setTimeout function.

What is a possible fix?

Thank You.

Upvotes: 0

Views: 2855

Answers (3)

sma
sma

Reputation: 9597

Another solution in addition to @pinturic's solution is to use ES6 arrow functions. If you're using ES6/Babel, etc., you can use an arrow function to bind to the lexical this.

navOpen() {
    this.setState({
        navStatus: "navShow",
        navLinesShow: false
    });
    if (!this.state.visible) {
        setTimeout(() => this.setState({visible: true}), 3000);
    }
}

Upvotes: 2

Aditya Singh
Aditya Singh

Reputation: 16660

It is because this doesn't have the correct value due to runtime binding. You need to use lexical binding. The best solution is to use ES6 arrow functions () => {} which provides lexical binding of this value. Even with the setTimeout() the lexical binding of this would fix the error you are getting

constructor() {
    super();

    this.state = {
        visible: false,
        navLinesShow: true
    };
}

navOpen = () => {
    this.setState({
        navStatus: "navShow",
        navLinesShow: false
    });

    if ( this.state.visible === false) {
        setTimeout(() => {
            this.setState({
                visible: true
             });
        }, 3000);
    }
}

Upvotes: 3

pinturic
pinturic

Reputation: 2263

Yes the problem is the setTimeout inside the setTimeout function "this" refer to the function itself: so the solution is the typical var that = this :

navOpen() {
this.setState({
    navStatus: "navShow",
    navLinesShow: false
});
if ( this.state.visible === false) {
 var that = this;
    setTimeout(function (){
        that.setState({
            visible: true
         });
    }, 3000);
}

Upvotes: 6

Related Questions