Loading


Consuming REST APIs In React With Fetch And Axios method.. The Complete React JS Developer Course 2023 [Videos].

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

What is Axios?

Promise based HTTP client for the browser and node.js

Axios is a JavaScript library for managing your codes ability to reach out to the web. Its common to use APIs to connect resources, exchange data, and access services.

However, accessing resources on the web is not an instantaneous process.  Thankfully, JavaScript has the Promise API. Promises are useful when performing asynchronous tasks. Asynchronous tasks can be thought of as things that do not block other things from happening.

For example, say you had to call your friend on the phone and fold laundry. Doing these tasks synchronously looks like:

  • Dial your friends number
  • Wait for them to answer
  • Talk to them
  • Start folding laundry

Doing these tasks asynchronously:

  • Dial your friends number
  • Start folding laundry
  • Wait for them to pick up
  • Talk to them

To understand how Promises fit into this example, consider that your friend made a promise to answer the phone when you called.

If they answer, the promise is resolved. and if they dont answer, the promise is rejected. Errors can be thrown when Promises are rejected.

Its a simple concept, but implementing Promises can be a bit tricky. Consequently, developers typically use tools like axios or fetch.

Whats the Difference Between Axios and Fetch?

They are quite similar! Both are HTTP client libraries. One difference is how each library handles response objects. Using fetch, the response object needs to be parsed to a JSON object:


The Axios library returns a data object that has already been parsed to JSON:


Axios library has a few other useful features.

  • Interceptors: Access the request or response configuration (headers, data, etc) as they are outgoing or incoming. These functions can act as gateways to check configuration or add data.
  • Instances: Create reusable instances with baseUrl, headers, and other configuration already set up.
  • Defaults: Set default values for common headers (like Authorization) on outgoing requests. This can be useful if you are authenticating to a server on every request.

Some of the features above overlap. Nonetheless, we are going to implement a few in the examples later to show where they can be useful. You can always view the Axios documentation on their NPM page for more information.

Why Use Axios with React?

If you are new to using React and APIs I would start with this Video, and then come back here. 

React is a JavaScript library for building user interfaces. Furthermore, reactive JavaScript frameworks (like React and Angular) sometimes need to revalidate data when a component mounts or when a page renders. This can lead to many requests between the front-end and back-end—or other external servers.

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.

Separate instances can be created for different APIs, interceptors are set up for global error handling, and defaults can be set, or unset, for things like common headers.

Axios can provide a little more functionality that goes a long way with applications that use React.

How to Display API Data with Axios in React (Axios React Tutorial)

In the example below, I am going to show you how to use Axios with React. However, I am abstracting away the project details, for now, so we can focus on Axios. Later we will put the code in the context of an application.

For this example, lets only consider two files: api.js and index.js. The first file holds the API call with Axios, and the second file is the React component that displays the data.

index.js

Here is index.js;


Its a simple React component that (from the top down):

  • imports React and a local file with the name api.js
  • creates a state variable to hold the response data
  • defines a function (fetchData) that calls a function on our imported object that contains the Axios call
  • displays the data using JSX and dot-notation to access data in the response object

api.js

The second file holds the Axios call. Lets build out this file to use Axios and some of its features. Starting with;


Now, we can easily add functions onto the api object while abstracting away some of the redundant details. However, what if you need to change the content type?

To override the default instance headers we can add the headers configuration onto the instance.


In the above file, we added the transformResponse parameter that defines a function.  The function parses the response, pulls data from the object, and returns the transformed data.

This can be a way to transform data before it hits the component. If the API call changes, or if the response object changes, the component doesnt care and we only have to change the API call.

Now that we have the basics of how to make an Axios API call and display data lets build something with Axios and React!

How to Build an Application with Axios and React (React App)

View the code on Github

Prerequisites

  • Node.js installed on your machine
  • Understanding of how to open a terminal, or command-line on your machine
  • Internet connection
  • Code editor (I am using Visual Studio Code)

Project Overview

The application will use Gatsby.js.

Gatsby is a static site generator that is recommended on Reactjs.org as the best way to build static websites with React. Its probably not the most relevant technology for the app we are going to build. However, its easy to set up a project and should be on your radar if you plan to create websites using React.

The project will use the Alpha Vantage API on to pull stock data and display closing prices on a graph. Soon, well get signed up on and subscribe to the free tier of the Alpha Vantage API.

1. Set-up the application

Open up a new terminal, or text editor and create a new folder named .

Change directories into the new folder and run the following commands:

$ npm init -y
$ npm install --save gatsby react-dom react axios recharts

The first command initializes an NPM project and the second installs the packages we need.

Create the folder src. Inside src add the folder pages and inside of pages add the file index.js. Next, add the following code to index.js.


The above file is very similar to our example earlier but with a few more variables, a form, and some styling. The API call, for the moment, is commented out because that function doesnt exist yet.

Finally, lets create two more files before we start the development server.

  • In the project root, add the file .env.development.
  • Inside src create the file api.js

The project structure should resemble the image below.

project structure

Run gatsby develop in the project root. After the development server starts, navigate to http://localhost:8000. You should see:

gatsby stock market app, analyze stock data

Selecting the dropdown in the top right allows you to view code snippets for specific endpoints and given parameters. The snippets can also be specific to certain libraries. We could grab code directly from the dashboard to save ourselves time.

This is normally a great place to start. For this app, however, you can just use the code below and add it to api.js.


Again, this code is similar to our example in the previous section.

API Key

Most API keys need to be kept secret and your key is no exception. It can be found on the API dashboard (I blacked mine out in the picture of the dashboard above).

If we were to hardcode the API key into this file it would be retrievable on the front-end or it could accidentally be committed to a repository. For this example application, we will be loading it in as an environment variable.

Copy this value from your dashboard and add the following line to .env.development replacing "yourapikey"  with the actual value.

Create a .gitignore file at the root of the project and add the following to it;

.cache
node_modules
public
.env.*
.env

Restart the development server so the new environment variable can be loaded in.

Add Chart to index.js

We downloaded the library recharts at the beginning of the project. Now, lets import the components we need and uncomment our function call in index.js.

The file should now have the code:


Theres a lot that can be done with recharts but explaining that library is outside the scope of this Video.

The new code adds the chart, and an API call can be made, but none of the data is displayed! Lets transform the data using Axios transformResponse configuration parameter.

5. Transform Axios Response Data

The dashboard can also be used for viewing sample response data. The sample response for the endpoint TIME_SERIES_DAILY_ADJUSTED isnt very friendly for what we want to do.

  1. The object parameters have spaces, so dot-notation isnt an option. This isnt that hard of a fix.
  2. The dates are keys for objects that contain the price data. Therefore, we cant iterate over the dates easily. The chart expects the date to be in the format { date: “2020-04-07”, closePrice: 102.00 }

Add the following transformResponse function to api.js:


Notice, after we transform the data, the object returned is easy for the component to handle. This is a nice benefit of Axios!

After making the final change, and entering a valid stock symbol, you should be able to view the daily close price for the stock!

finished stock market gatsby app

Great work! I hope you can see the simplicity and benefits of using Axios with React. You may have noticed that AlphaVantage has many endpoints to explore so dont stop here. Add more API calls and build out your stock market analysis tool.

Conclusion

You will see, or at least I have seen, many tutorials and videos that use Axios by default. It has become a popular library. It also can use the async/await keywords, but I prefer to only do that on the backend because async/await is not supported in IE or some older browsers.

I hope this has given you the confidence to use Axios in your next project and dont forget to save yourself some time by utilizing the dashboard to generate code snippets!


See All

Comments (79 Comments)

Submit Your Comment

See All Posts

Related Posts

React JS / Youtube

What is react JS vs react native?

React is the most popular javascript library for building user interfaces. It is fast, flexible and it also has a strong community sitting online to help you every time. The coolest thing about React is its based on components, you break down your complex code into individual pieces i.e components and that helps developers in organizing their code in a better way. A lot of companies are moving to React and thats the reason most of the beginners and experienced developers also expanding their knowledge learning this library.
27-jan-2021 /2 /79

React JS / Youtube

The Top 5 Programming Languages in 2022 to get a job.

The Top 5 Programming Languages in 2022 to get a job -React JS and React Native Tutorial The Complete Developer Course Part#2 [Urdu/Hindi]
27-jan-2021 /2 /79

React JS / Youtube

What is props in React?

Props is simply shorthand for properties. Props are how components talk to each other and the data flow is immutable. Props are passed down the component tree from parent to children and vice versa.
27-dec-2020 /2 /79