Twitch viewer: Need help with online/offline function

Twitch viewer: Need help with online/offline function
0

#1

I’m working on my Twitch project, but I still have one problem with my script. I’m having problems with a function I created to determine whether a user is online or not. This function is connected to an if/else statement and has been labeling all the users as offline. It almost seems like the function is not working at all Can someone tell me what I’m doing wrong or how I can improve.

function online(user) {
    var url = 'https://wind-bow.glitch.me/twitch-api/streams/' + user;
    var request = new XMLHttpRequest();
    request.open('GET', url);
    request.responseType ='json';
    request.send();
    var bool;
    request.onload = function () {
        if (request.response.stream === null) {
            bool = false;
        } else {
            bool = true;
        }   
    };
    
    return bool;
}

#2

I imagine you have something like:

if (online('freecodecamp') {
 // do something
}

You probably are using a variable or referencing an array element instead of ‘freecodecamp’, but you get the idea.

The problem with your code is that the return bool; executes before a response has come back from the GET request to the API endpoint. Why? Because the GET request is asynchronous and allows other code to continue executing before the response comes back. I have modified your original code with two console.log statements (see below). You will notice that the console.log right before the return bool; statement executes before the console.log inside the request.onload function. The reason you see undefined for bool, is because you declared it with var bool; and JavaScript automatically gives uninitialized variables the value undefined.

function online(user) {
    var url = 'https://wind-bow.glitch.me/twitch-api/streams/' + user;
    var request = new XMLHttpRequest();
    request.open('GET', url);
    request.responseType ='json';
    request.send();
    var bool;
    request.onload = function () {
        if (request.response.stream === null) {
            bool = false;
        } else {
            bool = true;
        }   
        console.log('finally got a response and bool = ' + bool);
    };
    console.log('returning current value of bool which is ' + bool);
    return bool;
}

if (online('freecodecamp')) {
 // do something
}

The above displays the following in the console:

returning current value of bool which is undefined
finally got a response and bool = false


#3

Thank you for the tip, it’s helping me along with what to do next. Good job at noticing how I used the if statement. Just changed up the structure, and I’m all set, thanks for the help!