-1

I have a class that has a member-variable name and a function getdata(). The function makes an API call and assigns the value it receives to the member variable

class Person
{
constructor()
    {
    this.name = this.getdata();
    }
getdata()
    {
    $.ajax({
          url: 'https://randomuser.me/api/',
          dataType: 'json',
          success: function(data) {
            console.log(data);
            this.name = data;
          }
        });
    }

}

But the value is not assigned.

I have also tried fetch:

class Person
{
constructor()
    {
    this.name = this.getdata();
    }
getdata()
    {

    fetch('https://randomuser.me/api/').then(function(response) {
                return response.json();
            }).then(function(j) {
            this.name = j                   
    });
    }

}

But it does not identify this inside the then function

Aseem Ahir
  • 623
  • 1
  • 6
  • 7
  • I have also tried using return statement instead of this.name inside the success blocks – Aseem Ahir Feb 06 '18 at 22:27
  • To 'close' voters: This might well be a duplicate of something else. But it's asking something different from the linked question, and the solution there does not answer this one. – Scott Sauyet Feb 07 '18 at 21:29

1 Answers1

0

You might want to look at a question on the use of this in JS. The this you assign to in the function is not what you're expecting.

The quickest fix is to do something like

// ...
getData: function() {
  const self = this;
  fetch(...).then(...
    self.name = j
  )
}

But using arrow functions would also fix this.

Scott Sauyet
  • 49,207
  • 4
  • 49
  • 103
  • I do understand your point, that when the fetch success function is called, the class object loses scope. however, that's my exact question. how do i point to the class object in the fetch function? And if that is not possible, how do I return the value to assign it to the class member variable – Aseem Ahir Feb 06 '18 at 22:34
  • I believe my (untested) answer does exactly what you're saying. (Or perhaps your comment came in before my edit was finished?) – Scott Sauyet Feb 07 '18 at 15:05
  • yes, I wrote that before the edit was finished. Great, the solution worked, Thanks – Aseem Ahir Feb 07 '18 at 19:42
  • Sorry, simply accidentally pushed the submit button before I was finished. Thought my edit would get in soon enough not to mark it as such. Oh well. – Scott Sauyet Feb 07 '18 at 21:30