Following
How to use async/await with axios in react
I am trying to make a simple get request to my server using Async/Await in a React.js App.
The server loads a simple JSON at /data
which looks like this
JSON
{
id: 1,
name: "Aditya"
}
I am able to get the data to my React App using simple jquery ajax get method. However, I want to make use of axios library and Async/Await to follow ES7 standards. My current code looks like this:
class App extends React.Component{
async getData(){
const res = await axios('/data');
console.log(res.json());
}
render(){
return(
<div>
{this.getData()}
</div>
);
}
}
Using this approach I get the following error:
Objects are not valid as a React child (found: [object Promise]). If you meant to render a collection of children, use an array instead.
Am I not implementing it correctly?
In my experience over the past few months, I've realized that the best way to achieve this is:
If you are trying to make post request on events such as click, then call
getData()
function on the event and replace the content of it like so:Furthermore, if you are making any request when the component is about to load then simply replace
async getData()
withasync componentDidMount()
and change the render function like so:Two issues jump out:
Your
getData
never returns anything, so its promise (async
functions always return a promise) will resolve withundefined
when it resolvesThe 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 resolutionAddressing #1:
getData
should return the result of callingjson
:Addressig #2: We'd have to see more of your code, but fundamentally, you can't do
...because that doesn't wait for the resolution. You'd need instead to use
getData
to set state:...and use that state when rendering:
Update: Now that you've shown us your code, you'd need to do something like this:
Futher update: You've indicated a preference for using
await
incomponentDidMount
rather thanthen
andcatch
. You'd do that by nesting anasync
IIFE function within it and ensuring that function can't throw. (componentDidMount
itself can't beasync
, nothing will consume that promise.) E.g.: