How to Use Async/Await with Axios in React

I am a front end developer at Morfsys and I enjoy writing about things related to web, technology and more.

In this piece, I’ll be covering how to best use async/await with Axios in React.

Installing AxiosFirst thing first, to get started, we’ll need to install Axios:npm install –save axiosMaking a Get RequestNext, let’s try to make a simple get request using Axios from our react component:The above code makes a get request to https://reqres.

in to retrieve a few users from their API and displays the user’s first name in our component.

Using Async/AwaitNow, we want to make the same request using async/await.

Let's do it!For a function to use await, we must wrap the function itself as an async function:An async function is different than a sync function in that an async function doesn’t block the processing of the code below it.

If you are trying to make a POST request, simply pass in the parameters as a second variable to Axios:axios.

post('https://yourdomain.

com', { name: 'Aditya' })To learn more about Axios, please visit https://www.

npmjs.

com/package/axios.

. More details

Leave a Reply