Facebook / Javascript API Display all data pulled not working

120 views Asked by At

Im trying to get all the messages from a facebook group post to display. with the code below:

   FB.api("/groupid/feed", function (response) {
    console.log(i + " : " + response.data.length);
    for (var i = 0; i < response.data.length; i++) {
        console.log(i + " : " + response.data[i].message);
        document.getElementById('posts').innerHTML = 'post: ' + i + ' : ' + response.data[i].message +'</br>';

    }

}) ;

I cant get the information in getElementId to show all the information that the console log shows. The console log shows 24 items and the website will just display 1 item. What do i need to change to get the information to display all 24 items not just the first one?

2

There are 2 answers

2
Danny Delott On

You are overwriting the innerHTML property in that for loop.

Instead, you should be appending it to the innerHTML.

Try this:

 FB.api("/groupid/feed", function (response) {
    for (var i = 0; i < response.data.length; i++) {
        console.log(i + " : " + response.data[i].message);
        document.getElementById('posts').innerHTML += 'post: ' + i + ' : ' + response.data[i].message +'</br>';
    }
 });

While you're at it, you can also refactor the loop entirely to use the native .forEach method.

It'll be cleaner, take a look:

 FB.api("/groupid/feed", function (response) {
    response.data.forEach(function(item, i){
      console.log(i + " : " + item.message);
      document.getElementById('posts').innerHTML += 'post: ' + i + ' : ' + item.message +'</br>';
    });
 });
0
andyrandy On

Basically Dannys answer with some improvements. Never use innerHTML in a loop, and you can cache the length (although it will not be a big difference):

var feed;
FB.api("/groupid/feed", function (response) {
    for (var i = 0, count = response.data.length; i < count; i++) {
        console.log(i + " : " + response.data[i].message);
        feed += 'post: ' + i + ' : ' + response.data[i].message +'</br>';
    }
    document.getElementById('posts').innerHTML = feed;
});

You could also cache response.data, of course. And i would definitely use a for loop instead of forEach. forEach is only supported in IE9+ (not that i care about IE8 anymore, but still). for is also a lot faster than forEach: https://jsperf.com/for-vs-foreach/37