Red
Red

Reputation: 33

Asynchronous function ahead of setState

I found solutions for functional programming, but I need solutions for programming in classes without use useEffect.
Code app:

import React from "react";
import "./styles.css";

class App extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      text: "hello"
    };
  }

  setText() {
    this.setState({
      text: "new text"
    });
    this.func();
  }

  async func() {
    console.log(this.state.text);
  }

  render() {
    return (
      <div>
        <button onClick={this.setText.bind(this)}>Click</button>
      </div>
    );
  }
}

export default App;

In the console, I see "hello". How to execute setState first and then its asynchronous function?

Upvotes: 1

Views: 31

Answers (1)

AmerllicA
AmerllicA

Reputation: 32472

Actually, the setState function act asynchronous, so you should use the callback of setState for calling the func function:

setText() {
  this.setState(
    {
      text: "new text",
    }, 
    this.func // callback of setState
  );
}

Then in the console, you can see new text.

Upvotes: 2

Related Questions