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?
This question is related to
javascript
json
reactjs
asynchronous
ecmascript-2017
Async/Await with axios
useEffect(() => {
const getData = async () => {
await axios.get('your_url')
.then(res => {
console.log(res)
})
.catch(err => {
console.log(err)
});
}
getData()
}, [])
In my experience over the past few months, I've realized that the best way to achieve this is:
class App extends React.Component{
constructor(){
super();
this.state = {
serverResponse: ''
}
}
componentDidMount(){
this.getData();
}
async getData(){
const res = await axios.get('url-to-get-the-data');
const { data } = await res;
this.setState({serverResponse: data})
}
render(){
return(
<div>
{this.state.serverResponse}
</div>
);
}
}
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:
async getData(username, password){
const res = await axios.post('url-to-post-the-data', {
username,
password
});
...
}
Furthermore, if you are making any request when the component is about to load then simply replace async getData()
with async componentDidMount()
and change the render function like so:
render(){
return (
<div>{this.state.serverResponse}</div>
)
}
Source: Stackoverflow.com