Sign in
Log inSign up

Data fetching with Axios in ReactJS

Praneeth_ Alluri's photo
Praneeth_ Alluri
·Oct 1, 2021·

5 min read

Introduction

I started a project on react, In which I needed to fetch data from API and I encountered some difficulties in fetching data. After some research over youtube and google, I understood the concept of Why we should actually use AXIOS to fetch data. I did realize few features and advantages of axios and let me discuss them and at the end of this blog, you will be able to get data from the server.

What is Axios?

Axios is a library that serves to create HTTP requests that are present externally. It is evident from the fact that we may sometimes in React applications need to get data from the external source. It is quite difficult to fetch such data so that they can be normally shown on the website.

Axios is a third party JavaScript Library. This means that Axios is used to send an HTTP request and handle their responses, all using JavaScript 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
  • Transform request and response data
  • Cancel requests
  • Automatic transforms for JSON data
  • Client side support for protecting against XSRF

Advantages of Axios

  • Supports older browsers.
  • Has a way to abort a request.
  • supports upload progress
  • Has a way to set a response timeout.
  • performs automatic JSON data transformation.

Why exactly we should use Axios over fetch data

Axios performs automatic transforms of JSON data. Fetch is a two-step process when handling JSON data- first, to make the actual request; second, to call the . json() method on the response. Axios allows cancelling request and request timeout.

Axios has some advantages, like protection against cross-site request forgery (CSFR) attacks. To be able to use the Axios library, users have to install it and import it to your project, using CDN, npm, Yarn, or Bower.

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. so, to install axios using npm, run npm install axios in your command prompt/VS code terminal which I had used.

Axios supports several request methods such as get,post,delet,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 argumetn(url).

axios.get(' ')

.then(response = > {

console.log(response);

Screenshot (11).png

The above code is a simple API fetch using axios which I had used in my project.

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.

Screenshot (13).png

In the code, we created an arrow function where we fetched data from the server and passed into a variable called fetchdata and called it in the lifecycle hooks. The second parameter [fetchurl] is an variable in which the url's are available, for now ignore the second parameter and it works with empty array (it means the hook runs just once).

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

note:- If you are fetching only one api data then use an empty array as second parameter which works only once.

_20211013_164315.JPG 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 in an Array:

_20211013_164333.JPG The above image contains collection of array and the results are displayed with key,title,backdrop_path etc.,

The output screen will be:

_20211013_164350.JPG

Error Handling

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

fmp24us9frc952a6tnbh.png

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

wlxdlyt41f8wzf8fz61y.png

Can we fetch data using async/await function

Yes, we can fetch data.

Screenshot (14).png

To use the async/await syntax, we need to wrap the axios.get() function call within the 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. I didn't use post function in my project so I don't have images to upload so I had to download it from internet

The below code is another way to post data using the async/await function.

w72fmhzxicri76tjgtx2.png

kuum4td5pkw5fc6klniw.png

Conclusion

In this blog, you have learned how to make http requests to the server using axios (an alternative to fetch data) 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. Iam sure this blog had made you axios journey a nice one. Feel free to practice what you have learnt.