1

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();
        }
Rolo
  • 17
  • 1
  • 5
  • `this` in your second and third `then` callbacks isn't a reference to your component anymore, because you're using traditional (`function`) functions. If you use arrow functions consistently (your first `then` handler is one, but the second two aren't), those arrow functions will close over `this` and it will refer to your component instance. – T.J. Crowder Oct 06 '18 at 16:52
  • Side note: You're not checking that the request succeeded. You're not alone, so many people fail to check that I wrote up the problem in a [post on my anemic little blog](http://blog.niftysnippets.org/2018/06/common-fetch-errors.html). Check `.ok` (or `.status`). – T.J. Crowder Oct 06 '18 at 16:53
  • That's really helpful, thank you so much! It's nice to understand why instead of just doing. Thanks again – Rolo Oct 06 '18 at 18:02

2 Answers2

-1

You are loosing this context so Change it to arrow function

  .then(() => {
                    this.setState({
                    sportsNewsFiltered: tempArr
                });
            });
Hemadri Dasari
  • 23,970
  • 25
  • 87
  • 133
-1

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 () {...}

Edward Lynch
  • 148
  • 8