0

I have the following variable

var brands = [];

Which I need to populate with some data. The data is comming from an API. I use Axios to perform a GET.

getRemoteBrands() {
    axios
      .get("http://my-url")
      .then(response => {
        response.data.forEach(element => {
          var instance =
          {
            label: element.brand,
            value : element.brand    
          };
          this.brands.push(instance);
        });
      }).catch(error => console.log(error));
  }

The following error is show in developer tools

TypeError: Cannot read property 'push' of undefined
    at index.js:104
    at Array.forEach (<anonymous>)
    at index.js:98

Obviously brands is not an array, but an object. How can I make this an array?

Tobias Moe Thorstensen
  • 8,861
  • 16
  • 75
  • 143

1 Answers1

1

var brands = []; creates a standalone variable. this.brands is not a standalone variable, it's a property of this, which is something entirely different (which sounds to be undefined in your case - you've never assigned anything to this.brands before).

Either refer to the standalone variable brands after creating it:

var brands = [];

class something {
  // ...
  getRemoteBrands() {
    var instance = {
      label: element.brand,
      value : element.brand    
    };
    brands.push(instance);
  }
}

Or create this.brands in the constructor, and refer to this.brands:

class something {
  constructor() {
    this.brands = [];
  }
  getRemoteBrands() {
    var instance = {
      label: element.brand,
      value : element.brand    
    };
    this.brands.push(instance);
  }
}
CertainPerformance
  • 356,069
  • 52
  • 309
  • 320