React setState reading as undefined after filtering through API response

59 views Asked by At

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();
        }
2

There are 2 answers

0
Hemadri Dasari On BEST ANSWER

You are loosing this context so Change it to arrow function

  .then(() => {
                    this.setState({
                    sportsNewsFiltered: tempArr
                });
            });
0
Edward Lynch On

So this in your set state is referring to the function its in not the react class as you want, to fix this simply have: () =>{...}

Instead of: function () {...}