Two issues jump out:
Your getData
never returns anything, so its promise (async
functions always return a promise) will resolve with undefined
when it resolves
The error message clearly shows you're trying to directly render the promise getData
returns, rather than waiting for it to resolve and then rendering the resolution
Addressing #1: getData
should return the result of calling json
:
async getData(){
const res = await axios('/data');
return await res.json();
}
Addressig #2: We'd have to see more of your code, but fundamentally, you can't do
<SomeElement>{getData()}</SomeElement>
...because that doesn't wait for the resolution. You'd need instead to use getData
to set state:
this.getData().then(data => this.setState({data}))
.catch(err => { /*...handle the error...*/});
...and use that state when rendering:
<SomeElement>{this.state.data}</SomeElement>
Update: Now that you've shown us your code, you'd need to do something like this:
class App extends React.Component{
async getData() {
const res = await axios('/data');
return await res.json(); // (Or whatever)
}
constructor(...args) {
super(...args);
this.state = {data: null};
}
componentDidMount() {
if (!this.state.data) {
this.getData().then(data => this.setState({data}))
.catch(err => { /*...handle the error...*/});
}
}
render() {
return (
<div>
{this.state.data ? <em>Loading...</em> : this.state.data}
</div>
);
}
}
Futher update: You've indicated a preference for using await
in componentDidMount
rather than then
and catch
. You'd do that by nesting an async
IIFE function within it and ensuring that function can't throw. (componentDidMount
itself can't be async
, nothing will consume that promise.) E.g.:
class App extends React.Component{
async getData() {
const res = await axios('/data');
return await res.json(); // (Or whatever)
}
constructor(...args) {
super(...args);
this.state = {data: null};
}
componentDidMount() {
if (!this.state.data) {
(async () => {
try {
this.setState({data: await this.getData()});
} catch (e) {
//...handle the error...
}
})();
}
}
render() {
return (
<div>
{this.state.data ? <em>Loading...</em> : this.state.data}
</div>
);
}
}