0

I'm very new to React. I am attempting to update a React component's state using an AJAX call, which returned a Deferred object's promise.

componentDidMount: function() {
     window.AlbumAPI.get_albums().then(function (response) {
     console.log(data);
     this.setState(data);
});

and the method the component is calling:

window.AlbumAPI = {
  get_albums: function() {
    var deferred = new $.Deferred();
    $.ajax({
     url: '/albums',
    }).done(function(res) {
     deferred.resolve(res);
    });
    return deferred.promise();
  }
};

The console log is returning the correct object, exactly what I expect it to be, a JS array. But the SetState() is throwing an undefined method for the following line:

.done(function(res)

In the component, I have tried using .when and .done in their correct syntax and am getting the same error regardless.

Nishit Maheta
  • 6,021
  • 3
  • 17
  • 32
idknox
  • 63
  • 5

1 Answers1

1

The solution was to bind the function, since it was an anonymous callback:

componentDidMount: function() {
     window.AlbumAPI.get_albums().then(function (response) {
         console.log(response);
        this.setState(response);
    }.bind(this));
}
idknox
  • 63
  • 5