I need help with my twitch status app


#1


As you can see, when you run the code, instead of returning the name of the user from the array twitchArray, it simply returns undefined.


#2

The problem is that by the time your callbacks run, your variable ‘x’ has a value of 8 (you can check this by logging it inside the callback. It seems like the most common way to solve this is to wrap the callback in another function that holds scope, as explained here https://stackoverflow.com/questions/7053965/when-using-callbacks-inside-a-loop-in-javascript-is-there-any-way-to-save-a-var (hope that helps?)


#3

I’ve reformatted and annotated your loop below that uses a global counter variable x

// all references to x below are to the same global x
for(x = 0; x < twitchArray.length; x++) {
  $.getJSON(
// this runs at time of iteration so global x is 0, 1, 2, ..., twitchArray.length
    twitchURL + twitchArray[x] + "?callback=?",
// this async callback runs when http response is received which is likely after loop has terminated
    function(user) {
// so global x is twitchArray.length
      console.log(twitchArray[x]);
    });
}

x is used in an async callback function in the loop body - by the time the callback for the http response runs the value of x is different from when the loop iteration ran

the fix below is to declare x with let which creates a different x for each iteration of the loop - the value of x in the callback will be the same when the loop iteration ran

// x is declared with block scope
// each iteration of the loop refers to a different variable x
for(let x = 0; x < twitchArray.length; x++) {
  $.getJSON(
// this runs at time of iteration so block scope x is 0, 1, 2, ..., twitchArray.length - 1
    twitchURL + twitchArray[x] + "?callback=?",
// this async callback runs when http response is received which is likely after loop has terminated
    function(user) {
// this retains a reference to the block scope x created per iteration so x is 0, 1, 2, ..., twitchArray.length - 1
      console.log(twitchArray[x]);
    });
}


Use the Twitchtv JSON API issue
#4

You need to use the Users API (https://wind-bow.glitch.me/twitch-api/users/) Endpoint to access display names and then the streams API for stream related things. Also you access json as json[“key”].