Table of Contents
What is Axios?
Promise based HTTP client for the browser and node.js
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.
Browse the Best Free APIs List
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 friend’s number
- Wait for them to answer
- Talk to them
- Start folding laundry
Doing these tasks asynchronously:
- Dial your friend’s number
- Start folding laundry
- Wait for them to pick up
- Talk to them
To understand how Promise’s 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 don’t answer, the promise is ‘rejected’. Errors can be thrown when Promises are rejected.
It’s a simple concept, but implementing Promises can be a bit tricky. Consequently, developers typically use tools like axios
or fetch
.
What’s 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:
fetch('/', { // configuration }) .then(response => response.json()) .then(response => { // do something with data })
The Axios library returns a data
object that has already been parsed to JSON:
axios({ url: '/', // configuration }) .then(response => { // do something with JSON response data })
Axios’s 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 article, 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, let’s 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
;
import React from 'react' import api from '../api' const IndexPage = () => { // Create state variables let [responseData, setResponseData] = React.useState('') // fetches data const fetchData = (e) => { e.preventDefault() api.getData() .then((response)=>{ setResponseData(response.data) console.log(response) }) .catch((error) => { console.log(error) }) } return ( <div> <h1>{responseData.title}</h1> <button onClick={(e) => fetchData(e)} type='button'>Click Me For Data</button> {responseData.dates && responseData.dates.map(date => { return <p>{date}</p> })} </div> ) } export default IndexPage
It’s 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. Let’s build out this file to use Axios and some of its features. Starting with;
import axios from 'axios' export default { getData: () => axios({ 'method':'GET', 'url':'https://example.com/query', 'headers': { 'content-type':'application/octet-stream', 'x-rapidapi-host':'example.com', 'x-rapidapi-key': process.env.RAPIDAPI_KEY }, 'params': { 'search':'parameter', }, }) }
This file creates an object that we import as api
in index.js
. There is a function called getData
on the object.
The Axios call takes a configuration object as the argument containing the:
- HTTP method
- URL
- headers
- query parameters
- etc.
Create an Axios Instance
Let’s say that this is a common Axios configuration, and we want to utilize Axios’s capabilities to keep our code a little more DRY and maintainable. Here’s how the code changes:
import axios from 'axios' // Create instance called instance const instance = axios.create({ baseURL: 'https://example.com', headers: { 'content-type':'application/octet-stream', 'x-rapidapi-host':'example.com', 'x-rapidapi-key': process.env.RAPIDAPI_KEY }, }); export default { getData: () => instance({ 'method':'GET', 'url':'/query', 'params': { 'search':'parameter', }, }), postData: () => instance({ 'method': 'POST', 'url':'/api', 'data': { 'item1':'data1', 'item2':'item2' } }) }
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?
Config order of precedence
Config will be merged with an order of precedence. The order is library defaults found in lib/defaults.js, then
defaults
property of the instance, and finallyconfig
argument for the request. The latter will take precedence over the former. …
To override the default instance headers we can add the headers configuration onto the instance.
import axios from 'axios' const instance = axios.create({ baseURL: 'https://example.com', headers: { 'content-type':'application/octet-stream', 'x-rapidapi-host':'example.com', 'x-rapidapi-key': process.env.RAPIDAPI_KEY }, }); export default { getData: () => instance({ 'method':'GET', 'url':'/query', 'params': { 'search':'parameter', }, }), postData: () => instance({ 'method': 'POST', 'url':'/api', 'data': { 'item1':'data1', 'item2':'item2' }, 'headers': { 'content-type':'application/json' // override instance defaults } }) }
Transform Axios Response Data
Another feature of Axios is transforming the response (or request) before the data is passed to the component.
Remember that I mentioned one of the differences between the fetch API and Axios is how the response object is handled?
We have access to the data object in the configuration before it reaches the component. This cleans up the code in the component but can add some visual complexity in the api.js
file. The choice is up to the developer where—or if—to format the response data. Regardless, let’s see where we can add this transformation in our file.
import axios from 'axios' const instance = axios.create({ baseURL: 'https://example.com', headers: { 'content-type':'application/octet-stream', 'x-rapidapi-host':'example.com', 'x-rapidapi-key': process.env.RAPIDAPI_KEY }, }); export default { getData: () => instance({ 'method':'GET', 'url':'/query', 'params': { 'search':'parameter', }, transformResponse: [function (data) { // Do whatever you want to transform the data console.log('Transforming data...') const json = JSON.parse(data) // list of nested object keys const dates = Object.keys(json['nested object']) data = { dates } return data; }], }), postData: () => instance({ 'method': 'POST', 'url':'/api', 'data': { 'item1':'data1', 'item2':'item2' }, 'headers': { 'content-type':'application/json' // override instance defaults }, }) }
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 doesn’t 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 let’s build something with Axios and React!
How to Build an Application with Axios and React (React App)
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 free and open source framework based on React that helps developers build blazing fast websites and apps
Gatsby is a static site generator that is recommended on Reactjs.org as the best way to build static websites with React. It’s probably not the most relevant technology for the app we are going to build. However, it’s 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 RapidAPI to pull stock data and display closing prices on a graph. Soon, we’ll get signed up on RapidAPI 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 rapidapi-display-axios-data-react
.
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
.
import React from 'react' import api from '../api' const IndexPage = () => { // Create state variables let [responseData, setResponseData] = React.useState('') let [ticker, setTicker] = React.useState('') let [message, setMessage] = React.useState('') // fetches stock data based on parameters const fetchData = (e) => { e.preventDefault() setMessage('Loading...') // api.stockTimeSeries(ticker) // .then((response)=>{ // setResponseData(response.data) // setMessage('') // console.log(response) // }) // .catch((error) => { // setMessage('Error') // console.log(error) // }) } return ( <div style={{ background: '#EEE', padding: '5%', fontFamily: '"Lucida Console", Monaco, monospace' }}> <h1 style={{ background: 'black', color: 'white', padding: '1rem', display: 'inline-block' }}>Gatsby Stock Market App</h1> <h2>Analyze Stock Data</h2> <form onSubmit={fetchData}> <fieldset> <legend>Search Stock Market</legend> <label htmlFor="ticker">Enter stock ticker <input required name="ticker" id="ticker" type='text' placeholder='SPY' value={ticker} onChange={(e) => setTicker(e.target.value)} /> </label> <button type='submit'>Submit</button> </fieldset> </form> <p>{message}</p> <h3>Symbol: {responseData ? responseData.symbol : ''}</h3> <p>Daily Time Series with Splits and Dividend Events</p> <small>Last Refresh: {responseData ? responseData.refreshed : ''}</small> </div> ) } export default IndexPage
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 doesn’t exist yet.
Finally, let’s create two more files before we start the development server.
- In the project root, add the file
.env.development
. - Inside
src
create the fileapi.js
The project structure should resemble the image below.
Run gatsby develop
in the project root. After the development server starts, navigate to http://localhost:8000. You should see:
2. Sign Up For a Free Account on RapidAPI
You will need an account on RapidAPI before subscribing to Alpha Vantage. Visit RapidAPI to get signed up if you haven’t already!
3. Subscribe to the Alpha Vantage API

Notice I have already subscribed to the Basic plan, therefore I have a link to Manage and View Usage that takes me to the developer dashboard.
You can track your API usage on the dashboard in case you have concerns about approaching your quota for any of the APIs that you subscribe to.
We get 500 requests a day for free and that is plenty for our small application!
4. Add Axios API Call
Before adding the code to api.js
take a look at the RapidAPI dashboard endpoints tab.
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
.
import axios from 'axios' const instance = axios.create({ baseURL: 'https://alpha-vantage.p.rapidapi.com', headers: { 'content-type':'application/octet-stream', 'x-rapidapi-host':'alpha-vantage.p.rapidapi.com', 'x-rapidapi-key': process.env.RAPIDAPI_KEY } }); export default { stockTimeSeries: (symbol) => instance({ 'method':'GET', 'url':'/query', 'params': { 'outputsize':'compact', 'datatype':'json', 'function':'TIME_SERIES_DAILY_ADJUSTED', 'symbol': symbol.toUpperCase() }, }) }
Again, this code is similar to our example in the previous section.
API Key
Most API keys need to be kept secret and your RapidAPI 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.
RAPIDAPI_KEY=yourapikey
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, let’s import the components we need and uncomment our function call in index.js
.
The file should now have the code:
import React from 'react' import api from '../api' import { LineChart, XAxis, CartesianGrid, Line, Tooltip, YAxis, Label } from 'recharts' // import components const IndexPage = () => { // Create state variables let [responseData, setResponseData] = React.useState('') let [ticker, setTicker] = React.useState('') let [message, setMessage] = React.useState('') // fetches stock data based on parameters const fetchData = (e) => { e.preventDefault() setMessage('Loading...') api.stockTimeSeries(ticker) // uncomment function call .then((response)=>{ setResponseData(response.data) setMessage('') console.log(response) }) .catch((error) => { setMessage('Error') console.log(error) }) } return ( <div style={{ background: '#EEE', padding: '5%', fontFamily: '"Lucida Console", Monaco, monospace' }}> <h1 style={{ background: 'black', color: 'white', padding: '1rem', display: 'inline-block' }}>Gatsby Stock Market App</h1> <h2>Analyze Stock Data</h2> <form onSubmit={fetchData}> <fieldset> <legend>Search Stock Market</legend> <label htmlFor="ticker">Enter stock ticker <input required name="ticker" id="ticker" type='text' placeholder='SPY' value={ticker} onChange={(e) => setTicker(e.target.value)} /> </label> <button type='submit'>Submit</button> </fieldset> </form> <p>{message}</p> <h3>Symbol: {responseData ? responseData.symbol : ''}</h3> <p>Daily Time Series with Splits and Dividend Events</p> <small>Last Refresh: {responseData ? responseData.refreshed : ''}</small> <LineChart width={900} height={500} data={responseData.closePrices} margin={{ top: 50, right: 20, left: 10, bottom: 5 }} > <YAxis tickCount={10} type="number" width={80}> <Label value="Close Price" position="insideLeft" angle={270} /> </YAxis> <Tooltip /> <XAxis padding={{left: 5, right: 5}} tickCount={10} angle={-60} height={90} dataKey="date" /> <CartesianGrid stroke="#f5f5f5" /> <Line type="monotone" dataKey="close" stroke="#ff7300" yAxisId={0} /> </LineChart> </div> ) } export default IndexPage
There’s a lot that can be done with recharts but explaining that library is outside the scope of this article.
The new code adds the chart, and an API call can be made, but none of the data is displayed! Let’s transform the data using Axios’s transformResponse
configuration parameter.
5. Transform Axios Response Data
The RapidAPI dashboard can also be used for viewing sample response data. The sample response for the endpoint TIME_SERIES_DAILY_ADJUSTED isn’t very friendly for what we want to do.
- The object parameters have spaces, so dot-notation isn’t an option. This isn’t that hard of a fix.
- The dates are keys for objects that contain the price data. Therefore, we can’t 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
:
.... .... transformResponse: [function (data) { // Do whatever you want to transform the data console.log('Transforming data...') const json = JSON.parse(data) const dates = Object.keys(json['Time Series (Daily)']).reverse() // Construct response data for chart input const closePrices = dates.map(date => date = { date, close: Number(json['Time Series (Daily)'][date]['4. close']) }) const symbol = json['Meta Data']['2. Symbol'] const refreshed = json['Meta Data']['3. Last Refreshed'] data = { symbol, refreshed, closePrices } return data; }], .... ....
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!
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 don’t 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 don’t forget to save yourself some time by utilizing the RapidAPI dashboard to generate code snippets!
FAQ
What is Axios?
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’s 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.
Why Use Axios with React?
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.
- How To Create a React App Using Typescript
- Learn more about Post Axios
I have an authorization with login app in order to get documents from a mongodb atlas collection,
implemented with a react frontend (client, src, etc) and a nodejs, express backend, with my get, post endpoints, implemented to get data through my mongodb connection.
My data consist from a ‘product’ collection with each document connected to a ‘user’ collection through the user id.
I need when pressing a button at the endpoint react frontend component , to pass the logged user id, straight to the backend, in order to select the appropriate connected to my user id, documents from my products collection.
For now, I have implemented up to the point that I can retrieve the data from my mongo connection, through my backend from my component in react frontend, without querying with the user id my product collection, using db. find(), and i can’t filter data with the user id , because I cannot retrieve it from the frontend.
How can I achieve this task? How tough can be?
I am new in react and nodejs, old in programming, please give me a hint to go on , because all my google search hours are going useless. It seems all like I am in a large maze . I need to get a path from the lot,
to get my results filtered with the user id, stack in the frontend!
Is that so?
Great thanks.
Great content, thanks!