GrapeJam
GrapeJam

Reputation: 181

'undefined is not an object' error when using this.setState within a setTimeout function

I am using a setTimeout function which runs on a loop alternating between a boolean state using setState. However when this.setState gets called in the function I receive the following error:

TypeError: undefined is not an object (evaluating: 'this.state.percentages')

Below is a snippet of the code I am using - I would be very grateful to anyone who can point out the mistake I am making:


constructor(props) {
    super(props);
    this.state = {
      percentages: false,
    };
  }      

loopPercentages() {
    setTimeout(function() {
      this.setState({ percentages: !this.state.percentages });
        loopPercentages();
    }, 10000);
}
    
componentDidMount() {
  this.loopPercentages();
}

Upvotes: 1

Views: 892

Answers (2)

lissettdm
lissettdm

Reputation: 13078

Use the setState callback function to get always the current state value:

loopPercentages() {
    setTimeout(() =>  { //--> this component scope
      this.setState((prev) => ({ percentages: !prev.percentages }));
      this.loopPercentages();
    }, 10000);
}

Upvotes: 1

Ivan Ignacio
Ivan Ignacio

Reputation: 31

import React from "react";

export class Test extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      percentages: false
    };
  }

  loopPercentages = () => {
    setTimeout(() => {
      this.setState({ percentages: !this.state.percentages });
      this.loopPercentages();
    }, 10000);
  };

  componentDidMount() {
    this.loopPercentages();
  }

  render() {
    return (
      <div>
        <h1>Hello StackOverflow</h1>
      </div>
    );
  }
}

Upvotes: 2

Related Questions