Twitch TV help, only displaying 1 person

Twitch TV help, only displaying 1 person
0

#1

I am doing the Freecodecamp Twitch TV project where I show if 9 streamers are online. I use this array to store the streamers:

Codepen: https://codepen.io/Mike-was-here123/pen/MOmKzO

var streamers = [
    "ESL_SC2",
    "OgamingSC2",
    "cretetion",
    "freecodecamp",
    "storbeck",
    "habathcx",
    "RobotCaleb",
    "noobs2ninjas"
  ];

I use these two API’s, I used a for loop which I explained later.

Channel/streamer details:

"https://wind-bow.gomix.me/twitch-api/channels/"+streamers[i]+"?callback=?"

Stream details (to check if their streaming)

"https://wind-bow.gomix.me/twitch-api/streams/"+streamers[i]+"?callback=?"

I used this code to access these API’s

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


    var channelApi = "https://wind-bow.gomix.me/twitch-api/channels/" +
      streamers[i] +
      "?callback=?";


    $.getJSON(streamStatusApi, function(data) {
      $.getJSON(channelApi, function(data2) {
       if(data.stream == null) {
        // here i pushed something into the html based on stream status
       } 

       else if (data.stream == true) {
          // here i pushed something  into based on stream status.
        }
      });
    }); // $.getJSON for stream status
  } // for loop

So why is only noobs2ninjas’s stream status being displayed on the html? Basically the last name in the array. Someone suggested that its because the two JSON’s are inside each other. I need information from both API’s. Would the variables still be global if they were separated (and made outside the JSON)?


#2

The problem is because you declared the streamStatusApi and channelApi variables with the var keyword. Such variables remain alive even after the for-loop (or block in general) they are in finished executing. It’s true that the outer .getJSON calls use the correct URLs, but the inner one uses the last value that the channelApi variable takes (which is the URL for noobs2ninjas).

You can peek at the values of these variables by “tapping” with a console.log:

$.getJSON((console.log({streamStatusApi}), streamStatusApi), function(data) {
  $.getJSON((console.log({channelApi}), channelApi), function(data2) {
    ...      

Declaring these variables with let makes them block-scoped, and they are alive only for each iteration of the for loop.


#3

In addition to what @kevcomedia said, your else if block of code will never execute, because stream is either going to be an object or the value null. Your code checks if stream is equal to true. You do not even need an else if, you just need an else.

else  if (data.stream == true) { // never going to be true

#4

Thanks guys, but how to lock my image in place (offline/ online)?