Welcome Guest! (App Version 3.1)

websitnero logo name

Making API Calls with Axios

React - API Calls with Axios

To make the API calls first of all install the 'axios' library, then go through the following steps to make the API hit.

  • In App.js include a new component <Home/>.
  • In Home component import Axios library to be used for API hit. In Life-Cycle hook of ComponentDidMount() make the API hit and store the return in state. User updated state to render UI with fetched values inside render() function.

Full Axios Example

Go through the following files to understand the full 'axios' implementation to make API hit in React:

App.js

import React from 'react';
import './App.css';
import Home from './components/home';

function App() {
  return (
    <div className="App">
      <Home></Home>
    </div>
  );
}

export default App;

home.js

import React, {Component} from 'react';
import axios from 'axios';

class Home extends Component {
  state = {
    users: []
  }

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

  render(){
    return(
      <div>
       {
        this.state.users.map((x) => (
          <div>
            <p>{x.name}, {x.email}</p>
          </div>
        ))
       }
      </div>
    )
  }
}

export default Home;

Output:

File Structure:

WebsiteNero is highly optimized for learning various website developing technlogies. We try our best to add maximum modules and examples to help learn the concepts clearly and vividly. We try to present all content and examples as simple as we can removing any complexity to hurdle easy understanding. We try best provide you with worthful content, but we cannot guarantee full correctness of all the content on this site. While using this website, you agree to have read and accepted all our terms of use and conditions, cookie, and privacy policy. Copyright, 2013-2018 by websitenero.com. All Rights Reserved.