DEV Community

Sarulatha
Sarulatha

Posted on

Fetch API using axios and fetch API

How to fetch API in react js

An api can be fetched by two ways using

1.Fetch api

2.Axios api

Let's see both the ways of how to fetch data from an API.

Fetch Api

Fetch api is a built in promise-based api. Let's look at an example,here we took json placeholder API which is generally used for testing.

img1

The above code explains the basic syntax of fetching data from an api.Now let us see how we can use them in our application to render the data in components.

img2

You can see that the fetch code block is now bounded with componentDidMount.The reason is that the data that we get from an API must be updated in states and re-rendered everytime. To make that work we are fetching data inside componentDidMount.

componentDidMount works only in class component,therefore when you fetch api data make sure that you are using class component

Also, we have declared states such as post,isLoading and error .

1.The post is used to store response data from api

2.error is used to store the error data if any error occurs.

You may be wondering why this isLoading is used and set to true.Normally,it takes some time for an api to fetch data from the endpoints.Until the data is fetched ,we are setting the value of isLoading to true then after fetching we are setting the data to false.

img3

Here comes the main part where we are going to render the data from api.

1.First we are checking if there is any error while fetching data.If any error occures we are displaying the user that there is some error.

2.Next we are checking whether isLoading is true or false.If it's true we are indicating user that the data is still loading to display. When the data gets fetched it's set to false so the else part of the block gets rendered.

3.We are storing the API data in an array called post in our state. So, we are using map function to render each data in the component.The key value is the id of the object to identify unique data.

I think that's enough for fetch API.We can now see how can we fetch api using Axios.

Axios API

Unlike Fetch api axios is not a build-in api. So,we need to install it.

Alt Text
Then,import the axios in your file where you are going to fetch data.

Alt Text

Here we can see the major difference is that we didn't convert the response into a json object by using

.then=>response.json()

There are many advantages and disadvantages of using both axios and fetch api.You can refer it from here.

There is no much difference in the remaining parts of the code which is similar to the previous one.

Alt Text
Thats all about fetching data from an api.Hope you guys understand well.Thanks for reading :-)

Top comments (0)