Question about TwitchTV for loop (Solved)

Question about TwitchTV for loop (Solved)
0

#1

Hi FCC family,

I was trying to use a for loop together with JQuery to add the logos of different TwitchTV users to the webpage. When I console log individual logos, the correct urls all show up.

However, when I append the HTML elements with the logo url (as a variable), the logos show up incorrectly.

Could someone tell me how to solve this problem?

Thanks so much!

 var Streamers = ["ESL_SC2", "OgamingSC2", "cretetion", "storbeck", "habathcx", "RobotCaleb", "noobs2ninjas"];
   
   for (i = 0; i < Streamers.length; i++) { 
   
     var name = Streamers[i];
     var urlLogo="https://wind-bow.gomix.me/twitch-api/channels/" + Streamers[i] + "?callback=?";
     var urlStatus="https://wind-bow.gomix.me/twitch-api/streams/" + Streamers[i] + "?callback=?";
     $.getJSON(urlLogo, function(data1){
   var logo = data1.logo;
     console.log(logo);
       $('#block0').after("<div class='block text-center'>" + 
                        "<div class='row'><div class='col-md-2'><img src=" + logo + "></img></div>" +
                        "<div class='col-md-2'><h3>" + "name" + "</h3></div>" +
                        "<div class='col-md-8'><h3>" + "status" + "</h3></div></div></div>");
     
     });
    
   };

The codepen project is here.


#2

What are you expecting to see? I’m seeing logos.


#3

Somehow the logos show up inconsistently - from my end a lot of the logos are just that of FreeCodeCamp, for example.

I’ve updated the code, adding the username, and status variables. But the same problem occurs. The codepen project is here –

var Streamers = [“ESL_SC2”, “OgamingSC2”, “cretetion”, “storbeck”, “habathcx”, “RobotCaleb”, “noobs2ninjas”];

for (i=0; i<Streamers.length; i++){
var userName = Streamers[i];
var userLogo;
var userStatus;
var urlLogo=“https://wind-bow.gomix.me/twitch-api/channels/” + Streamers[i] + “?callback=?”;
var urlStatus=“https://wind-bow.gomix.me/twitch-api/streams/” + Streamers[i] + “?callback=?”;
$.getJSON(urlLogo, function(data1){
userLogo = data1.logo; });

   $.getJSON(urlStatus, function(data2){
     
      if(data2["stream"]===null){

userStatus = “Offline”;}
else {userStatus = “online”;}
console.log(userStatus);});

   $('#block0').after("<div class='block text-center'>" + 
                    "<div class='row'><div class='col-md-2'><img src=" + userLogo + "></img></div>" +
                    "<div class='col-md-2'><h3>" + userName + "</h3></div>" +
                    "<div class='col-md-8'><h3>" + userStatus + "</h3></div></div></div>");

};


#4

Hi all,

I solved my own problem …

This StackOverflow post saved my life – https://stackoverflow.com/questions/15347750/getjson-and-for-loop-issue

when I added a function(i) to embed all code within a for loop, that solved the problem somehow …

The updated Codepen is here –