Using Async await in react component
I think you need more about async/await
in JS.
An async function
always return a promise.
So x
in Wrapper
is a promise. Because you don't use await/async
.
It should be like this.
async Wrapper = (body) => {
try{
let x = await this.Send(body); // <-- missing await here
return x;
}catch(e){console.log(e)}
}
But then, the code in render
doesn't work. because this.Wrapper()
now returns a promise. -> returnData is a promise
. And the render
method can't be async function :)
render(props) {
//...
const returnData = this.Wrapper(jsonBody) // <-- returnData here is a promise.
//...
So to make things work.
You have to use state
. Call the this.Wrapper
in componentDidMount
or componentDidUpdate
. For example:
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
}