I'm trying to filter an api response in React to certain news items, but when I call the setState function my console is throwing the error that it cannot setState of property undefined. I'm new to React so excuse me if this is an obvious fix.
class LeagueTables extends Component {
constructor(props) {
super();
this.state = {
sportsNewsFiltered: []
};
this.mountNews = this.mountNews.bind(this);
}
mountNews() {
var tempArr = [];
var urlNews =
"https://newsapi.org/v2/top-headlines?sources=bbc-
sport&apiKey=" + SECRETS.API_KEY;
var reqNews = new Request(urlNews);
fetch(reqNews)
.then(response => response.json())
.then(function(json) {
for (var i = 0; i < json.articles.length; i++) {
if (json.articles[i].url.includes("football")) {
tempArr.push(json.articles[i]);
}
}
})
.then(function() {
this.setState({
sportsNewsFiltered: tempArr
});
});
}
componentDidMount() {
this.mountNews();
}
You are loosing this context so Change it to arrow function