0

I'm using a custom API to fetch data. I have an object that contains each data to be fetched, so everything is dynamic. At the point had to fetch data using the fetch() function. Now a request is been made when the component is mounted (componentDidMount). Since I'm using an object to fetch for each Json data, I'll have to map this object.

componentDidMount(){
    CATEGORIES.map(function(category){
        this.fetchApiData(category.key);
    });
}

Now I have defined my fetchApiData() properly. It actually works without mapping but doesn't when I map the object.

2 Answers2

1

You are trying to access this inside of another function which does not have access to fetchApiData property. To use the enclosing context, use fat-arrow based function:

componentDidMount(){
    CATEGORIES.map((category) => {
        this.fetchApiData(category.key);
    });
}
Sunny R Gupta
  • 5,026
  • 1
  • 31
  • 40
Spider
  • 140
  • 6
0

The context of this changes inside the map's callback function. You can assign this to a variable and use that inside the map's callback function.

componentDidMount(){
    var that = this;
    CATEGORIES.map(function(category){
        that.fetchApiData(category.key);
    });
}
cdoshi
  • 2,772
  • 1
  • 13
  • 20