Sometimes, we want to use Async/Await with Axios in React.js.
In this article, we’ll look at how to use Async/Await with Axios in React.js.
How to use Async/Await with Axios in React.js?
To use Async/Await with Axios in React.js, we can use it in a function.
For instance, we write
const axios = require("axios").default;
const sendGetRequest = async () => {
try {
const resp = await axios.get("https://jsonplaceholder.typicode.com/posts", {
headers: {
authorization: "Bearer YOUR_JWT_TOKEN_HERE",
},
});
console.log(resp.data);
} catch (err) {
console.error(err);
}
};
sendGetRequest();
to define the sendGetRequest
function.
In it, we call axios.get
to make a get request.
And then we get the response body from resp.data
.
We get the error from err
.
Conclusion
To use Async/Await with Axios in React.js, we can use it in a function.