Using Axios to make API calls in React

Axios is an HTTP client to make API calls. It is also promise based by default as in it is asynchronous. Though we can use the fetch API in react Axios provides certain benefits like cross-browser compatibility, automatic transformation of response to JSON, ability to cancel requests, and more. The only caveat is that it adds a memory footprint to the project size which I feel can be ignored for most cases.

To setup Axios in react projects you can use either NPM or Yarn like so

npm install axios --save
yarn add axios

once the packages are installed they will have to be imported and used as shown in the code example below.

import React from 'react';
import axios from 'axios';

class App extends React.Component{

  state = {
    posts: []
  }

  componentDidMount() {
    const apiCall = async () => {
      const response = await axios.get('https://jsonplaceholder.typicode.com/posts');
      this.setState({ posts: response.data })
    }
    apiCall();

  }
  render() {
    console.log(this.state)
    return (
      <div>
        {this.state.posts.map((post) => {
          return <h3 key={post.id}>{post.title}</h3>
        })}
      </div>
    )
  }
}

export default App;
import React from 'react';
import axios from 'axios';

class App extends React.Component{

  state = {
    posts: []
  }

  componentDidMount() {
    axios.get('https://jsonplaceholder.typicode.com/posts')
      .then(response => {
        this.setState({ posts: response.data })
      })

  }
  render() {
    console.log(this.state)
    return (
      <div>
        {this.state.posts.map((post) => {
          return <h3 key={post.id}>{post.title}</h3>
        })}
      </div>
    )
  }
}

export default App;

The above examples are for the GET method to use the POST method and to pass information via post see the code below.

 const apiCall = async () => {
        const response = await axios.post('https://jsonplaceholder.typicode.com/posts',
          {
            postTitle:'New Post'
          });
      this.setState({ posts: response.data })
    }
    apiCall();

Subscribe to UIUXTEK Newsletter

One update per week. All the latest posts directly in your inbox.