Display Fetched Data on Browser Using Axios in React.

Antriksh Singh
3 min readJun 15, 2021

--

from google images

In this blog, we will be seeing how to extract data with axios library by creating a simple CRA project and saving the data in a useState() Hook in react , then displaying the data in a React Component.

WHAT IS AXIOS?

Axios is a Promised base JavaScript library for managing your code’s ability to reach out to the web. It’s common to use API’s to connect resources, exchange data, and access services.

from google images

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. If you wanna read more feel free to checkout the documentation 😊

Importing axios and making a GET request

Hit npm install axios

to install axios and then import it in the JavaScript file where data extraction will take place.

Now that axios is installed, we can use it to make a GET request to retrieve data from any API endpoint. Our aim is to store this request inside a unique function.

  1. I created a simple CRA project and imported the dependencies in the App.js file. We create a simple method and call it any name in my case getpost() which will handle the response by using the axios GET method.

Since Axios is a promise-based library, so the promise must be handled. I am going to use “then” to handle the promise which will store the whole response automatically into JSON format . One big and nice feature in axios library and Axios helps to keep things D.R.Y with instances, interceptors, and defaults. This can help with complex applications that are frequently making API requests.

2. Next, we added a button with an eventHandler and some basic styles with Tailwind CSS. Which when clicked the function is called and makes an axios request to the API.

3. Now to call all the data received in getpost() function, just add a span or a p tag of HTML and return this line of code .

4. Just run your app by typing npm start in your terminal and check the browser . You will see a random joke appearing on the screen when the button is clicked.

Refresh to get a new set of jokes . Cheers🎉😊 we have now successfully called our data within our browser using axios in React.

--

--