Tuco Tuco - 20 days ago 8
Javascript Question

Best way to access API from React App?

What's the best way for me to access an API using a React app? The API is currently developed in Golang using kami & mgo for the POST/GET/DELETE requests.

I want to be able to make a GET request to the following URL:

http://user:password@localhost:8000/api/v1/systems

on my React app and store the result in a state attribute:

this.state = {
data: //store the data here
}


I also want to load this data whenever the page is loaded so maybe I should use the componentDidMount() function to handle this?

I've never used API calls on React, so I was wondering if anyone here could tell me a good way to this?

EDIT

I'm using React 15.3.2.

EDIT #2

I've taken a look at fetch to handle the requests, but I'm still unsure how to use it in my situation. I've got the react app running on localhost:3000 and the api running on localhost:8000, /api/v1/systems will return a JSON with the following format:

{ systems : [ //list of objects ] }


I've tried the following inside my componentDidMount():

fetch(myRequest)
.then(result => {
console.log(result);
//this.setState({ data: result.json() });
});


Not too sure what myRequest should be (been trying with a simple string of the URL: 'http://localhost:8000/api/v1/systems') and I'm also not sure if the ports where the apps are running could make a conflict or something.

Answer

You will have to decide on a library to do API calls. A simple way is to use fetch, which is built-in in modern browsers. There's a polyfill to cover older ones. jQuery's AJAX or SuperAgent are two alternatives. Here's a simple example using fetch. You'll only have to change the URL of the request.

class Example extends React.Component {
  constructor() {
    super();
    this.state = { data: {} };
  }
  componentDidMount() {
    var self = this;
    fetch('http://reqres.in/api/users')
      .then(function(response) {
        return response.json()
      }).then(function(data) {
        self.setState({ data }, () => console.log(self.state));
      });
  }
  render() {
    return (
      <div/>
    );
  }
}

ReactDOM.render(<Example/>, document.getElementById('View'));
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js"></script>
<div id="View"></div>

Comments