DEV Community

Cover image for Data fetching with Axios in React made simple
adams mercy
adams mercy

Posted on

Data fetching with Axios in React made simple

Introduction

I started a project on react which I was new to some months ago and I got to a point I needed to fetch data from the server and I encountered some difficulties trying to fetch data from API. After some research and practice, I understood the concept and was able to fetch data in some other projects. My aim is to work you through on how to get started with axios and understand the necessary and basic part so as not to get stuck. At the end of this article, you will be able to get and post data to a server.

Prerequisite

This project app is built with Material UI and React. A little knowledge of react will be helpful.

What is Axios?

Axios is a third party JavaScript library. Axios is a promise-based HTTP client easy to use for both browser and node.js.

Axios is a Promised-based JavaScript library that is used to send HTTP requests. You can think of it as an alternative to JavaScript's native fetch() function.

Axios is a modern, Promise-based HTTP client library. This means that Axios is used to send an HTTP request and handle their responses, all using JavaScript's promises. Axios supports both Node.js and JavaScript in the browser.

Features of axios

  • Make XMLHttpRequests from the browser
  • Make http requests from node.js
  • Supports the Promise API
  • Intercept request and response
  • Transform request and response data
  • Cancel requests
  • Automatic transforms for JSON data
  • Client side support for protecting against XSRF

Where do we make http request?

In a class based component, requests are made in componentDidMount() lifecycle while in a functional component, requests are made in react lifecycle hooks i.e. useEffect.
To use Axios, axios needs to be installed in your project and imported in the component you want to fetch data in. To install axios using npm which I used, run "npm install axios" in your command prompt.
Axios supports several request methods such as get, post, delete, put, etc.
Our major focus will be on get and post method which is commonly used.

Fetching data in Axios using the Get method

Axios offers a get method with at least one argument (url).

For example, let's see axios in action:

axios.get(' ')
.then(response => {
console.log(response);
});

Alt Text

The above code is a simple API fetch using axios. Now, let's explain:

Axios uses promises and get returns a promise 'then' which is a method which takes a function as the input and the function will get executed once the promise resolves, that is when the data from the server is there.

Alt Text

In the code, we create an arrow function where we fetched data from the server and passed in into a variable called getRepo and called it in the lifecycle hooks. The second parameter [ ] empty array was passed so that the lifecycle hooks runs just once.

Among the response gotten back from the API, we only need to display the data, that is why we stored response.data inside myRepo container and then passed it to the state.

Alt Text

The above image shows how the data fetched is being consumed or used in my component. Since the data returned is an array, we map through the array and then get the data we want to display and display it at the appropriate element.

The output will be:

Alt Text

Alt Text

Error Handling

If we have a network failure or if we make mistakes in the url, how do we handle this error?

Alt Text

To handle this error, add a catch method which catches any error you get, after the then method.

.catch ((error) {
console.log(error)
});

Output: Error handled properly

Alt Text

Another way to get or fetch data from the server using the async/await function

Alt Text

To use the async/await syntax, we need to wrap the axios.get() function call within an async function. We encase the method call with a try…catch block so that we can capture any errors. The variable “response” that receives the http data had to use await to ensure the asynchronous data was received before continuing.

How to Post data to the Server

Post method takes url as the input but also needs a second argument which is the data you want to send. You can also pass a third argument to configure the request. You can listen to the request and print it in the console.
The below code is another way to post data using the async/await function.

Alt Text

Alt Text

Conclusion

In this article, you have learned how to make http requests to the server using axios (an alternative to fetch) and we have been able to get data from server and also post data to the server using both promise and async/await which is a great start. I am sure this article has made you axios journey a nice one. Feel free to practice what you have learnt and exploit other axios request methods.

Top comments (9)

Collapse
 
vikramiiitm profile image
Vikram Choudhary

Thank you

Collapse
 
vinodkumardv profile image
VinodKumarDV

Nice explanation with example

Collapse
 
hasanrashed profile image
Kamrul Hasan Rashed • Edited

Bunch of thanks

Collapse
 
biomanuel profile image
Biomanuel

Wow! This is awesome. Thanks for sharing.

Collapse
 
yashpatel profile image
YashPatel12345

Thanks a lot

Collapse
 
hey_yogini profile image
Yogini Bende

Well explained 👏

Collapse
 
m_adams1909 profile image
adams mercy

Thanks

Collapse
 
stanleenwosu profile image
Stanley Nwosu

Great article..

Collapse
 
hadihammurabi profile image
Hadi Hidayat Hammurabi

And implement finite state machine