0

I'm working through freecodecamp and am stuck on a project where I have to get the statuses of a list of Twitch streams. The API response doesn't contain the name of the stream I am querying so I can't figure out how to make the connection from the stream name to the response. I've tried several things, but I can just not figure this out.

Here's the jsfiddle of my current attempt

Code looks something like this:

  var twitchApiEndpoint = "https://wind-bow.glitch.me/twitch-api";
  var streamsToGet = ["ESL_SC2", "OgamingSC2", "cretetion", "freecodecamp", "storbeck", "habathcx", "RobotCaleb", "noobs2ninjas"];
  var streamsStatuses = [];
  $(document).ready(getEntries);

  function getEntries() {

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

      $.getJSON(twitchApiEndpoint + "/streams/" + streamsToGet[i], function(json) {
        if (json.stream == null) {
          var streamStatus = "offline";
        } else {
          var streamStatus = json.stream.game;
        }

        $(".main").append('<div class="row stream-entry" id="' + i + '"><div class="col stream-title">' + streamsToGet[i] + '</div><div class="col stream-description">' + streamStatus + '</div>');

      });
    }

  }
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="container-fluid">
  <div class="row">
    <div class="col">
      <div class="title">
        <h1>Twitch Monitor</h1></div>
    </div>
  </div>
  <div class="main">
    <div class="row stream-entry">
      <div class="col stream-title">
        Name
      </div>
      <div class="col stream-description">
        Playing
      </div>
    </div>
  </div>
</div>
F0XS
  • 1,271
  • 3
  • 15
  • 19
  • 3
    Put actual code in SO not Pseudocode – Satpal Jan 29 '18 at 09:41
  • You need to use a closure as the AJAX call is async, where the loop is not. Therefore `i` is not what you expect it to be in the callback: https://jsfiddle.net/3wx26ubx/2/ – Rory McCrossan Jan 29 '18 at 09:43
  • 1
    Welcome to Stack Overflow! Please take the [tour], have a look around, and read through the [help], in particular [*How do I ask a good question?*](/help/how-to-ask) Please update your question with a [mcve] demonstrating the problem, ideally a **runnable** one using Stack Snippets (the `[<>]` toolbar button; [here's how to do one](https://meta.stackoverflow.com/questions/358992/ive-been-told-to-do-a-runnable-example-with-stack-snippets-how-do-i-do-tha)). The code must be **in** the question, not just linked. – T.J. Crowder Jan 29 '18 at 09:44
  • https://stackoverflow.com/q/750486/4374566 – Agney Jan 29 '18 at 09:46

0 Answers0