jlittlejohn
5/2/2019 - 4:44 AM

REACT: API Call Example

REACT: API Call Example

constructor(props) {
  super(props);
  this.state = {
    items: []
  };
}

componentDidMount() {
  fetch("http://example.com/api/endpoint/")
  //fetch("https://cors.io/?http://example.com/api/endpoint/")
    .then(response => response.json())
    .then(responseData => {
      this.setState({
        items: responseData.results
      });
    })
    .catch(error => {
      console.log("Fetching and parsing data error", error);
    });
}

render() {
  let items = this.state.items;
  console.log(items);
  return (
    <div>
      {items.map(function(item) {
        return (
          <h4 key={item.id}>
            {item.name}
          </h4>
        );
      })}
    </div>
  );
}