I tried to use async await in React for the first time. Just looking for feedback on whether this is the best way to implement it or if there is a better way?
Thanks in advance
You don’t need to async/await
componentDidMount()
. Just use it as usual:
componentDidMount(){
this.getData();
}
And async/avait
should be wrapped in try/catch
block:
this.getData = async () => {
try {
const res = await fetch(
this.state.recent ? this.state.last30 : this.state.allTime
);
const json = await res.json();
this.setState({ records: json }, () => console.log('done'));
} catch (e) {
// handle error
console.error(e);
}
};
1 Like
Thanks man, missed the componentDidMount() when I refactored.