Search code examples
javascriptreactjsaxiosapiary.ioapiary

Apiary API endpoint returning null data when called from web


I have a mock API in Apiary where if I hit my endpoint with cURL or just in the browser, it returns:

[
{
  "id": 1,
  "user_id": 1,
  "status": "Review"
  "name": "New York Songwriter",
  "negotiable": true,
  "description": "",
  "created_at": "2015-02-09T02:29:58 +08:00",
  "modified_at": "2015-02-17T05:30:17 +08:00"
},
{
  "id": 2,
  "user_id": 1,
  "status": "Accepted"
  "name": "Licensing Contract",
  "negotiable": false,
  "description": "Third party licensing agreement",
  "created_at": "2015-02-09T02:29:58 +08:00",
  "modified_at": "2015-02-17T05:30:17 +08:00"
}
]

I have a React app where I'm hitting this endpoint with axios in a function that is called in componentWillMount:

  componentWillMount() {
    this.loadItems();
  }

  loadItems() {
    var self = this;
    axios({
      url: ENDPOINT,
      method: 'get',
      responseType: 'json'
    })
    .then(function(r) {
      console.log(r);
      var d = r.data;
      self.setState({
        agreements: d
      });
    })
    .catch(function(r) {
      console.log(r);
    });
  }

The console.log I get a status 200 in the response, but data is null. What am I doing wrong?


Solution

  • Thanks to Mayank Shukla for the answer in the comments. The key is to use the native axios GET method, like so:

    axios.get(ENDPOINT)
      .then(function (response) {
        console.log(response);
      })
      .catch(function (error) {
        console.log(error);
      });
    

    Because the native GET has all the properties built in. In my example I hadn't defined all necessary properties.

    Thanks again, Mayank!