Search code examples
javascripttwitter

Unable to read text property using Twitter and Node


In my attempt to do a deep dive with javascript and node, I'm trying to build a small twitter application to collect the last 10 tweets with a given hashtag - the issue arises after the 9 tweet is collected and logged to the console. Depending on the hash tag (I tried #happy earlier in the day, and the program ran without issue), the program either runs as expected or throws and error thinking that the text property is undefined. My code is below:

var twit = require('twit')
var config = require('./config.js')


var twitter = new twit(config);

twitter.get('search/tweets', { q: '#happy', count: 9 }, function(err, tweets) {

  for (var i = 0; i < 10; i++) {
    if (tweets.statuses[i].text) {
      var tweet = tweets.statuses[i].text
      console.log(i)
      console.log(tweet);
    }
  }
});

The error I'm receiving after the 9th tweet is displayed in the console is as follows:

/Users/seanwelch/Desktop/statusboard/app.js:10
    if (tweets.statuses[i].text) {
                          ^

TypeError: Cannot read property 'text' of undefined

Solution

  • You're trying to access a property that doesn't exist, it's possible there aren't 10 tweets with that #hashtag?

    I would suggest rewriting your for loop to something along these lines

    for (var i = 0; i < tweets.statuses.length; i++) {
        var tweet = tweets.statuses[i].text
        console.log(i)
        console.log(tweet);
    }