Making API calls using Axios

Karuna Sehgal
Karuna Sehgal
Published in
2 min readMay 1, 2018

During the process of building out an React app that works with a Rails 5.1 API, I had to consider an approach on how to make a React component talk to the Rails API endpoint for getting all the data and display them successfully. I had to make an AJAX call to the API in a componentDidMount() lifecycle method of the React Component and store the data in the state.

There is more than one way for making API calls. One approach is using the axios library for making the API calls. One can also use fetch or jQuery if you prefer those.

I decided to use the axios library. The first thing I did was install axios with npm:

npm install axios --save

Then import it in the React component:

import axios from 'axios'

And use it in componentDidMount():

componentDidMount() {
axios.get('http://localhost:3001/api/v1/items.json')
.then(response => {
console.log(response)
this.setState({ideas: response.data})
})
.catch(error => console.log(error))
}

So axios is a Promise based HTTP client for the browser and node.js. It’s features include:

Make XMLHttpRequests from the browser

  • Make http requests from node.js
  • Supports the Promise API
  • Intercept request and response
  • Transform request and response data
  • Cancel requests
  • Automatic transforms for JSON data
  • Client side support for protecting against XSRF

Here is a list of Axios methods:

On a side note, axios does not have an “update” method, but rather uses “put” to modify an existing record. The word “update,” though, is used by the Rails API to name the endpoint.

Thank you for reading this blog post and hope you learned something new!

--

--

Karuna Sehgal
Karuna Sehgal

Woman on a mission - to live the best life possible!!