Error with JSON data from the Twitch TV API

I am having trouble with the Twitch API. When a streamer is live, I work with the "Stream" property, but if they are not streaming, I need to refer to another link. I use the getJSON function to fetch the necessary API link and work with it. However, my loop is not functioning correctly. It only displays the last streamer in the "channels" array instead of all those who are not streaming. I can't seem to figure out what the issue is. Help...

JSFiddle: https://jsfiddle.net/e7gLL25y/

JS Code:

var getJSON = function(url, callback) {
    var xhr = new XMLHttpRequest();
    xhr.open("GET", url, true);
    xhr.onload = function() {
        if(xhr.readyState == 4 && xhr.status == "200") {
            callback(JSON.parse(xhr.responseText));
        }
    };
    xhr.send();
};

var channels = ["summit1g", "esl_RuHub_CSGO", "Starladder1", "Senpai_Frozen", "tehvivalazz", "ESL_CSGO"];
var client_id = "hx3dea4ifwensxffoe8iwvekwvksnx";
var section = document.getElementById("main-section");

var streamer = [];
for(var i = 0; i < channels.length; i++) {

    var url_channels = "https://api.twitch.tv/kraken/channels/" + channels[i] + "?client_id=" + client_id;
    var url_streams = "https://api.twitch.tv/kraken/streams/" + channels[i] + "?client_id=" + client_id;

    getJSON(url_streams, function(response) {
        if( response["stream"] !== null ) {
            streamer[i] = document.createElement("div");
            streamer[i].className = "streamer";
            streamer[i].innerHTML = "<a target='_blank' href='" + response.stream.channel["url"] + 
                                        "'><img id='streamer-image' src='" + 
                                        response.stream.channel["logo"] + 
                                        "' alt='Av' /><h2 id='streamer-name'>" + 
                                        response.stream.channel["name"] + 
                                        "</h2><p id='stream-status'>" + 
                                        response.stream["game"] + "</p></a>";
            section.appendChild(streamer[i]);
        } else {
            getJSON(url_channels, function(r) {
                streamer[i] = document.createElement("div");
                streamer[i].className = "streamer";
                streamer[i].innerHTML = "<a target='_blank' href='" + r["url"] + 
                                            "'><img id='streamer-image' src='" + 
                                            r["logo"] + 
                                            "' alt='Av' /><h2 id='streamer-name'>" + 
                                            r["name"] + 
                                            "</h2><p id='stream-status'>Offline</p></a>";
                section.appendChild(streamer[i]);
            });
        }
    });

}

Answer №1

One common misunderstanding surrounds JavaScript contexts.

To delve into this issue further, check out my response linked here:

In essence, the getJSON response is triggered after looping through the entire array, causing i to hold the final index across all responses. To prevent its incrementation, a separate context must be established to store the value of i.

for(var i = 0; i < channels.length; i++) {

    var url_channels = "https://api.twitch.tv/kraken/channels/" + channels[i] + "?client_id=" + client_id;
    var url_streams = "https://api.twitch.tv/kraken/streams/" + channels[i] + "?client_id=" + client_id;
    (function(i) {
        // By encapsulating in another context, 'i' remains unaffected by external loops
        getJSON(url_streams, function(response) {
            // Actions based on the response...
        });
    })(i);

}

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Experiencing a console error which reads: "SyntaxError: Missing ) after argument list."

While working on configuring a new React CSR app and incorporating some boilerplate libraries, I encountered an error in the console: Uncaught SyntaxError: missing ) after argument list (at @emotion_react_macro.js?v=30f6ea37:29894:134) I am hesitant to ma ...

breezejs: Non-scalar relationship properties cannot be modified (Many-to-many constraint)

Utilizing AngularJS for data-binding has been smooth sailing so far, except for one hiccup I encountered while using a multi-select control. Instead of simply adding or removing an element from the model, it seems to replace it with a new array. This led t ...

What is the best way to manage returning to the original page that was loaded when utilizing the History API?

I'm in a bit of a pickle here. I've been using History.js with the History API and everything was going smoothly until I encountered an issue. Let's start with a simple page setup like this: <div ="header"> Header </div> <d ...

What is the best way to trigger a JavaScript function to execute as soon as the innerHtml has been modified via Ajax

Utilizing Ajax to dynamically update the content of a div upon clicking a link is my current project. I am seeking guidance on how to call a JavaScript function once the file has been retrieved from the server and the div's content has been replaced. ...

Ensure every individual input field in a Bootstrap form is validated using JavaScript before submitting the form

As a newcomer to Javascript, I am seeking assistance with validating each field in the form below without having to click on the submit button. Your help is greatly appreciated! <form action="" id = "form1" class = "form-group row"> & ...

injecting javascript dynamically using jquery

I am attempting to conditionally load a script in the case that the browser being used is IE8. To achieve this, I have employed jQuery's .getScript function as it allows me to execute certain actions after the script has been loaded. The issue lies in ...

What is the best way to format a condensed script into a single line?

There are times when the script in the web browser is packed into one line like function a(b){if(c==1){}else{}}. I have attempted to locate something that would display it in a more normal format. function a(b) { if(c==1) { } else { } } Howev ...

Instructions on adjusting the image size within a MUI Card

import { Card, CardActionArea, CardContent, CardMedia, Typography, } from "@mui/material"; import React from "react"; import { styled } from "@mui/material/styles"; const CardImage = styled("div")(({ theme ...

The background-size:cover property fails to function properly on iPhone models 4 and 5

I have taken on the task of educating my younger sister about programming, and we collaborated on creating this project together. Nicki Minaj Website However, we encountered an issue where the background image does not fully cover the screen when using b ...

Checking Sudoku Solutions on Codewars

I have come across this JavaScript code which seems to be functioning correctly. However, I am curious about the line board[3][8] != board[8][3] and how it checks for repeating row and column numbers. Can someone please provide an explanation? Thank you! ...

Loading modules conditionally in Nuxt.js

In my Nuxt.js configuration, I have included a module for Google Tag Manager like this: modules: [ [ '@nuxtjs/google-tag-manager', { id: 'GTM-XXXXXXX' } ] ] Everything is functioning properly, but I am curious ab ...

Am I implementing the Vue.JS onChange function correctly?

After selecting an option from mod_accs_Role_ID, how can I display the corresponding data stored in the database based on that selection? For example, if I select 1 in mod_accs_Role_ID, then the role_Name 'Hello' should be displayed. <div clas ...

A step-by-step guide to incorporating expandable and collapsible images within a div element using X

I have successfully created dynamic divs with some data that expand and collapse perfectly. Now I am looking to add expand and collapse images on these divs. I am relatively new to designing in xslt. <xsl:template match="category[key!='org.model.C ...

Using Python to interact with forms and click JavaScript buttons

Is there a way to automate form filling on a website by setting specific parameters that will bring up products matching those parameters? I attempted to use mechanize in python, but it does not support javascript. It seems like the process of entering par ...

Keep track of the user's email address as they complete the form

I currently use a Google Form to gather information from employees who work in remote locations Emp No * Punch * Customer details / mode or travel All the data collected is stored in a Google spreadsheet structured as follows: Timestamp Emp No Punch ...

Automatically closing the AppDateTimePicker modal in Vuexy theme after selecting a date

I am currently developing a Vue.js application using the Vuexy theme. One issue I have encountered is with a datetimepicker within a modal. The problem arises when I try to select a date on the datetimepicker component - it closes the modal instead of stay ...

What is the best way to adjust the size of a Div slideshow using

I need help with creating a slideshow that covers my webpage width 100% and height 500px. The image resolution is 1200*575. Can someone assist me with this? CSS #slide{ width : 100%; height: 500px; } HTML <!DOCTYPE html> <html> ...

Display tables based on selected changes with dynamically changing options

My HTML structure displays rows with active and inactive statuses based on a select change, and it's currently functioning correctly. However, the project requirements have changed, allowing for more status options besides just active and inactive. I ...

Top ways to avoid default on anchor tags: best practices for preventing this issue

Previously, excluding the criticism for not using unobtrusive JS, I typically employed anchors with inline onclick attributes for AJAX loading in the following format: <a href="http://example.com/some/specific/link.php?hello=mum" class="menu" id="m ...

Creating and deleting HTML elements in a dynamic array format

My current approach involves utilizing jQuery and JavaScript for the purpose of dynamically adding and removing HTML elements. Specifically, I am focusing on the removal of particular HTML elements. The code snippet is as follows: $(document).ready(fun ...