An example of API call in React.js

There are different types of Application Programming Interfaces(API). APIs are a mechanism for providing interaction between two applications using a set of rules. APIs are very necessary since we can add specific functionalities to our application. An example for API is bloggers using their twitter handle on their blog’s sidebar or footer. WordPress or any CMS allows this by using Twitter’s API. Different types of API are open APIs, Partner APIs, Internal APIs, Composite APIs. There are also different types of Web Services APIs. They are SOAP, REST, XML-RPC, JSON-RPC. 

Let’s see an example of API calls in React.js when using jQuery and AJAX.

export default class UserList extends React.Component {

  constructor(props) {

    super(props);


    this.state = {person: []};

  }


  componentDidMount() {

    this.UserList();

  }


  UserList() {

    $.getJSON('https://randomuser.me/api/')

      .then(({ results }) => this.setState({ person: results }));

  }


  render() {

    const persons = this.state.person.map((item, i) => (

      <div>

        <h1>{ item.name.first }</h1>

        <span>{ item.cell }, { item.email }</span>

      </div>

    ));


    return (

      <div id="layout-content" className="layout-content-wrapper">

        <div className="panel-list">{ persons }</div>

      </div>

    );

  }

}


In this example we have used an ajax call inside componentDidMount and updated state.