Setting State in a setTimeout method

Posted on

in

If you do:

setTimeout(function(){ 
      this.setState({something: "changed"}); 
    }, 1000);

You’ll get an error saying “this.setState is not a function”. To fix it for a class function, put it in a function (in this case handleClick() ), bind it in the constructor and use an arrow function in the setTimeOut:

constructor(props) {
    super(props);
    this.state = {
      something: false
    };
    //bind
    this.handleClick = this.handleClick.bind(this);
  }

//put in function
handleClick(e){
    this.setState(prevState => ({
      con1: !prevState.somthing
    }));
  }

//use arrow function
setTimeout(() => {this.handleClick()}, 1000);

For a function component, also use an arrow function but you’ll also need to use useRef to get the most current value of the state in case it changes before setTimeout is called:

const [something, handleClick] = useState(false);

  const somethingRef = useRef(something);
  somethingRef.current = something;

setTimeout(() => {handleClick(!somethingRef.current)}, 1000);

Leave a Reply

Your email address will not be published. Required fields are marked *

About me

Mark Wong is a front end developer with 10+ years experience. Most of his knowledge of HTML5, CSS and Js is self taught.

Calendar

May 2024
M T W T F S S
 12345
6789101112
13141516171819
20212223242526
2728293031