Raj Rj Raj Rj - 4 months ago 19
Javascript Question

what is right way to do API call in react js?

I have recently moved from Angular to ReactJs. I am using JQUERY for API call here. I have a API which give random user list, which i have to print in a list. I am not sure how do i write my API call. what is the best practice for that. I tried it but I am not getting the output. I am open to implement other library also for API calls. Below is my code.

import React from 'react';

export default class UserList extends React.Component {
constructor(props) {
super(props);
this.state = {
person: []
};
}

UserList(){
return $.getJSON('https://randomuser.me/api/')
.then(function(data) {
return data.results;
});
}

render() {
this.UserList().then(function(res){
this.state = {person: res};
});
return (
<div id="layout-content" className="layout-content-wrapper">
<div className="panel-list">
{this.state.person.map((item, i) =>{
return(
<h1>{item.name.first}</h1>
<span>{item.cell}, {item.email}</span>
)
})}
<div>
</div>
)
}
}

Answer

In this case you can do ajax call inside componentDidMount, and then update state

export default class UserList extends React.Component {
  constructor(props) {
    super(props);

    this.state = {person: []};
  }

  componentDidMount() {
    this.UserList();
  }

  UserList() {
    return $.getJSON('https://randomuser.me/api/')
      .then((data) => {
        this.setState({ person: data.results });
      });
  }

  render() {
    const persons = this.state.person.map((item, i) => {
      return <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>
  }
}