async await react stackoverflow code example

Example: async await react stackoverflow

constructor() {
    // ...
    this.state = { returnData: null }
}
async componentDidMount() {
   const returnData = await this.Post(...); // Using await to get the result of async func
   this.setState({ returnData });
}

async Post(body) {
  try{
    const options = {
      method: 'POST',
      uri: 'XXXXXXXXXXXXXXXXXXXX',
      body: body
    }
    return rp(options); // define await then return is unnecessary 
  }catch(e){console.warn(e)}
}

render() {
     const { returnData } = this.state;
    // ... Do the rest

}

Tags:

Misc Example