Handing Twitch Offline Streamers JSON

Handing Twitch Offline Streamers JSON
0.0 0

#1

Hi,

So I’m working on the Twitch Streaming site and I got into a hiccup, for some reason .stream === null isn’t working.

I’ve tried looking at console and for reasons unknown, it’ll only show the data from streams that are online and freecodecamp which is offline is not shown.

Here’s my JS code

var vidThumbs = document.getElementsByClassName('vidThumbs');

//JSON
var streamers = ["ESL_SC2", "OgamingSC2",  "admiralbulldog", "ESL_SC2", "OgamingSC2",  "admiralbulldog", "freecodecamp"];

/**
 * Create thumbnails based on streamers
 */
for (var index = 0; index < streamers.length; index++) { 
    var createDiv = document.createElement("div");
    createDiv.className = "vidThumbs";
    
    var vidStreams = document.getElementById("vidStreams");
    vidStreams.appendChild(createDiv);

    jsonRequest(streamers[index], index);
}

function jsonRequest(streamer, thumbnailNo) {
    var request = new XMLHttpRequest();
    request.open('GET', `https://wind-bow.glitch.me/twitch-api/streams/${streamer}`, true);
    request.onload = function () {
        if (request.status >= 200 && request.status < 400) {
            // Success!
            // console.log("success");
            var data = JSON.parse(request.responseText);
            var dataImagePreview = data.stream.preview.large;
            // console.log(data);
            // console.log(dataImagePreview);
            console.log(data.stream);
            if (data.stream === null) {   // THIS PART NOT WORKING
                console.log("true");
                vidThumbs[thumbnailNo].style.backgroundColor = `#000`;
            }
            vidThumbs[thumbnailNo].style.backgroundImage = `url(${dataImagePreview})`;

            
        }
        else {
            // We reached our target server, but it returned an error
            console.log("failed");
        }
    };  
    request.onerror = function () {
        console.log("an error occured"); 
    };
    request.send();
}

/**
 * Determine thumbnail sizes depending on thumbnail quantity
 */
var vidStreamsHeight = document.getElementById('vidStreams').offsetHeight;
var vidThumbsQty = vidThumbs.length;

for (var index = 0; index < vidThumbsQty; index++) {
    if (vidThumbsQty >= 4) {
        //2 rows video thumbnail
        vidThumbs[index].style.height = `${vidStreamsHeight / 2 - 20}px`;
        vidThumbs[index].style.width = `${(vidStreamsHeight / 2 - 20) * 1.5}px`;
    } else {
        //single row video thumbnail
        vidThumbs[index].style.height = `${vidStreamsHeight - 20}px`;
        vidThumbs[index].style.width = `${(vidStreamsHeight - 20) * 1.5}px`;   
    }
} 

#2

Here are some ways you can check:

if (variable == null) {...}
if (Boolean(variable) === false) {...}
if (typeof null === "object") {...}

#3

Hmm, I think I know why it’s not working and it’s related to request.onload which now I know only loads live streams.

But isn’t .onload sort of a requirement to get JSON to work? How would I get it to load even if the stream is offline?


#4

Try using xhttp.onreadystatechange = function() instead of onload. Might work better.
https://www.w3schools.com/xml/xml_http.asp


#5

Thanks, I tried it and doesn’t seem to work. Still scratching my head on why request.onload/request.onreadystatechange will not process an offline stream.

//JSON
var streamers = ["ESL_SC2", "OgamingSC2",  "admiralbulldog", "ESL_SC2", "OgamingSC2",  "admiralbulldog", "freecodecamp"];

for (var index = 0; index < streamers.length; index++) { 
    jsonRequest(streamers[index], index);
}

function jsonRequest(streamer, thumbnailNo) {
    var request = new XMLHttpRequest();
    request.open('GET', `https://wind-bow.glitch.me/twitch-api/streams/${streamer}`, true);
    // console.log(request.onreadystatechange);
    request.onload = function () {
        //if (request.status >= 200 && request.status < 400) {
        if (request.readyState == 4 && request.status == 200) {
            var data = JSON.parse(request.responseText);
            var dataImagePreview = data.stream.preview.large;
            // console.log(dataImagePreview);
            console.log(data);  // the result of this is in the photo attached after
            if (data.stream === null) {
                console.log("true");
                vidThumbs[thumbnailNo].style.backgroundColor = `#000`;
            }
            vidThumbs[thumbnailNo].style.backgroundImage = `url(${dataImagePreview})`;            
        }
        else {
            // We reached our target server, but it returned an error
            console.log("failed");
        }
    };  
    request.onerror = function () {
        console.log("an error occured"); 
    };
    request.send();
}

As you can see, it doesn’t process FreeCodeCamp stream as it’s offline


#6

You should be seeing an error in the console related to the following line:

 var dataImagePreview = data.stream.preview.large;

because for freecodecamp there will not be a preview property, because stream is null.

You need a slight logic change. Change the following:

        if (request.readyState == 4 && request.status == 200) {
            var data = JSON.parse(request.responseText);
            var dataImagePreview = data.stream.preview.large;
            console.log(data);  // the result of this is in the photo attached after
            if (data.stream === null) {
                console.log("true");
                vidThumbs[thumbnailNo].style.backgroundColor = `#000`;
            }
            vidThumbs[thumbnailNo].style.backgroundImage = `url(${dataImagePreview})`;            
        }
        else {
            // We reached our target server, but it returned an error
            console.log("failed");
        }

to the following:

        if (request.readyState == 4 && request.status == 200) {
            var data = JSON.parse(request.responseText);
            console.log(data);  // the result of this is in the photo attached after
            if (data.stream === null) {
                console.log("true");
                vidThumbs[thumbnailNo].style.backgroundColor = `#000`;
            }
            else {
              var dataImagePreview = data.stream.preview.large;
              vidThumbs[thumbnailNo].style.backgroundImage = `url(${dataImagePreview})`;      
            }
           
        }
        else {
            // We reached our target server, but it returned an error
            console.log("failed");
        }

#7

Wow thanks! That worked!

Yes, I did get that error, and I kept looking at freecodecamp JSON wondering why null isn’t working even though there’s data.stream in its JSON file.

So I guess what I should’ve have done in this case is to figure out how to handle the XMLHttpRequest.responseText for streams that are online and offline, as my original program didn’t do this?

One more thing, I noticed that people use different XMLHttpRequest response code, I’ve read about the meaning of 200, 400 and etc. but what I don’t get is, why would people use different combinations like so:

request.status >= 200 && request.status < 400
request.readyState == 4 && request.status == 200

As I’ve tried both and it works.


#8

You can take a look at all of the status codes here and readyState codes here.

I would stick with request.readyState == 4 && request.status == 200, because you want to make sure it is done (request.readyState == 4) and the request succeeded (request.status == 200).


#9

Hey all, I finally completed the project! Yippie!

Comments and constructive criticism appreciated :slight_smile: