1

So I'm doing a freeCodeCamp project that shows information regarding specific streamers. I have bumped into multiple problems, regarding if statements inside a for loop (I think).

First, the Status is always "Offline" for every streamer, second, the borders around the logos don't change except for the first one. If it worked, I'm still not sure whether the border colors would be correct though (red for offline streams, green for online).

If you watch closely, what I did was I provided a specific id for each iteration of streamer info, 1 for the corresponding image, and 1 for status, so I can target them with the i variable inside an if statement.

Here is the JS code, it is better visible via Codepen using the link I provided, mainly because you see the whole work and I don't know how to format code properly so that you don't have to use horizontal scrollbar to see long lines. :/

Thanks in advance!

$(document).ready(function() {

  var channels = ["freecodecamp", "wudijo", "ThijsHS", "HSdogdog", "Sjow"]; 

  for (var i = 0; i < channels.length; i++) {
       var channelURL = "https://wind-bow.gomix.me/twitch-api/channels/"+ channels[i] +"?callback=?";
       var streamURL = "https://wind-bow.gomix.me/twitch-api/streams/"+ channels[i] +"?callback=?";

   $.getJSON(channelURL, function(data1) {

     var logo = data1.logo;
     var name = data1.display_name;
     var twitchLink = data1.url;
     var status;

   $.getJSON(streamURL, function(data2) {

         if (data2.stream === null) {
           status = "Offline"; 
            }
         else {
           status = data2.stream.channel.status;
            }

    $("#followerInfo").append("<div class = 'row'><div class = 'col-md-4'><a href = '"+ twitchLink +"' target = 'blank'><img id = 'img"+ i +"' src = '"+ logo +"'></a></div><div class = 'col-md-4'><p>" + name + "</p></div><div class = 'col-md-4'><p id = 'status"+ i +"'>" + status + "</p></div></div>");

         if (data2.stream === null) {
           $("#img"+ i +"").addClass('img-offline');
          }
         else {
           $("#img"+ i +"").addClass('img-online');
          }

        });           
     });

 }

});
Zsolax
  • 15
  • 5

1 Answers1

0

If you console.log(channelURL) you can see that only "Sjow" his data is being called. This happens because your loop finishes before any requests are made, therefore only the last value in the array (Sjow) is used.

You can fix this by following this answer.

Niels de Bruin
  • 705
  • 5
  • 15
  • Great to hear! If you could mark my answer as the solution that'd be much appreciated :) – Niels de Bruin Jan 04 '18 at 13:18
  • Marked it! I thought it doesn't work because it only showed 1 online streamer for a while, while there was two. My guess is that the FCC-provided API pass-through requests data at higher time intervals? Hope it is not the code's fault. – Zsolax Jan 04 '18 at 14:20