Reputation: 5488
Im working through this example and would appreciate some help understanding the following section of code.
async componentDidMount() {
const { match: { params } } = this.props;
const question = (await axios.get(`http://localhost:8081/${params.questionId}`)).data;
this.setState({
question,
});
}
I haven't seen the string async
before componentDidMount()
up until now. What does this achieve? I know that after all the elements of the page are rendered correctly this method is called but what is async doing here?
Please help me understand what const { match: { params } } = this.props;
is doing here?
Upvotes: 0
Views: 227
Reputation: 3264
1.
You declare a function async
when you want to use await
inside that function to wait for an asynchronous call to return. I don't think you can use async
on componentDidMount
but you can use a promise instead:
componentDidMount() {
const { match: { params } } = this.props;
axios.get(`http://localhost:8081/${params.questionId}`)
.then(res => {
const question = res.data;
this.setState({ question });
});
}
2.
This is called destructuring, it means that you want to extract params
from this.props
const { match: { params } } = this.props;
It is equivalent to:
const params = this.props.match.params
Upvotes: 2