0

Without async &/or with prevState, I could not console.log the needed state of page right after setting a new state of page.

Since I've been doing some backend stuff I started learning how async works. So I figured maybe I can use await before this.setState to get the right state for the if statement that has to come right after setting the state.

changePage = async (newPage) => {
  if(this.state.page !== newPage){
    await this.setState({ page: newPage});
    console.log(this.state.page);
    if(this.state.page === ''){

    }else if(this.state.page === ''){

    }
  }
}

But I've never really seen this before nor ever used it in this way, so I am wondering is there a better way to do this?

Emile Bergeron
  • 17,074
  • 5
  • 83
  • 129

1 Answers1

0

In a class component, setState takes a callback that runs after the state update. So you don't really need to use async or await and can just do:

this.setState({ page: newPage}, () => {
  console.log(this.state.page);
  if(this.state.page === ''){

  }else if(this.state.page === ''){

  }
});
Brian Thompson
  • 13,263
  • 4
  • 23
  • 43