Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

React setting state with async/await

So I am setting my state in my constructor with:

constructor(props: IProps) {
    super(props);
    const nav = NavService.getNav();
    const user = AuthService.getProfile();

    this.state = {
        activeNav: 0,
        nav: nav ? nav : [],
        showDropdown: false,
        showNavDropdown: false,
        user: user ? user : [],
    };
}

However, I am noticing some async issues so I want to make getNav() and getProfile() async and await them. Obviously I can't do this in the constructor because constructors cannot be async and therefore I cannot use await. Now I know I can just throw this into an async componentDidMount() but this causes a double render(). How can I optimize this?

like image 973
L. Norman Avatar asked Aug 29 '26 11:08

L. Norman


1 Answers

I think a re-render will be hard to avoid if your have to load some data asynchronously.

You could keep an additional state variable loading and just return null in the render method until your data has loaded.

Example

class App extends React.Component {
  state = {
    activeNav: 0,
    nav: [],
    showDropdown: false,
    showNavDropdown: false,
    user: [],
    loading: true
  };

  componentDidMount() {
    Promise.all(NavService.getNav(), AuthService.getProfile())
      .then(([nav, user]) => {
        this.setState({ nav, user, loading: false });
      })
      .catch(error => {
        this.setState({ loading: false });
      });
  }

  render() {
    const {
      activeNav,
      nav,
      showDropdown,
      showNavDropdown,
      user,
      loading
    } = this.state;

    if (loading) {
      return null;
    }

    // ...
  }
}
like image 134
Tholle Avatar answered Aug 31 '26 03:08

Tholle



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!