0

I am having two different functions for google analytics. I am trying to call a function from another function. I am getting an error that says TypeError: this is undefined. I cannot understand why?

handleAccounts = (response) => {
  var details = response.result.items;
  console.log(response);
  this.setState({
    info: details
  });
  details.map(function(x) {
    gapi.client.analytics.management.webproperties
      .list({accountId: x})
      .then(this.handleProperties.bind(this)); //This is the line where I am getting the Error.
  });
}

handleProperties = (response) => {
  // Handles the response from the webproperties list method.
  if (response.result.items && response.result.items.length) {
    // Get the first Google Analytics account
    var firstAccountId = response.result.items[0].accountId;

    // Get the first property ID
    var firstPropertyId = response.result.items[0].id;

    // Query for Views (Profiles).
    //queryProfiles(firstAccountId, firstPropertyId);
    console.log(response);
  } else {
    console.log('No properties found for this user.');
  }
}
3
  • 2
    try changing details.map(function(x){ to details.map(x => { Commented Oct 12, 2017 at 0:03
  • you have to bind "this" to your arrow function, arrow functions don't automatically assume "this"
    – Mehrad
    Commented Oct 12, 2017 at 0:04
  • It's working now. Thanx a lot :)
    – Parth
    Commented Oct 12, 2017 at 0:20

1 Answer 1

2

If these functions are being called from within a component then you need to bind them within the components constructor or componentDidMount. Binding is necessary to make 'this' work in the callback as class methods aren't bound by default in React.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.