-2

I am trying to get five (5) articles from a news API and to push those results into a blank array titled "topNews"

I believe the issue lies in the getNews function listed below not writing to the blank array created at the top of the file.

The fetch is working and I can see the array coming back with .then((result) => console.log(result))

I am trying to push it into the new array that I call in the next function to display the results but when I console.log the topNews array with, I get undefined.

Any help would be appreciated.

let twitterTrends = [];
let topNews = [];
let numOfCompleted = 0;

function getTrends() {
  var myHeaders = new Headers();
  myHeaders.append(
    "Authorization",
    "Bearer ********");
  myHeaders.append(
    "Cookie",
    'personalization_id="v1_QSZs3kHuqI6knlNtIbIchQ=="; guest_id=v1%3A159630901122767291'
  );

  var requestOptions = {
    method: "GET",
    headers: myHeaders,
    redirect: "follow",
  };

  const url =
    "https://cors-anywhere-gp.herokuapp.com/https://api.twitter.com/1.1/trends/place.json?id=23424977";

  fetch(url, requestOptions)
    .then((response) => response.json())
    .then((responseJson) => topFive(responseJson))
    .catch((error) => console.log("error", error));
}

function topFive(responseJson) {
  $("#results").html("<h2>Loading Twitter Trends...</h2>");
  for (let i = 0; i < 5; i++) {
    $("#results").append(`<p>${responseJson[0].trends[i].name}</p>`);
    twitterTrends.push(responseJson[0].trends[i].name);
    setTimeout(
      () => getNews(responseJson[0].trends[i].name.replace("#", ""), i),
      2000
    );
  }
  showTrends();
}

function getNews(topic, index) {
  var requestOptions = {
     method: "GET",
  };

  var params = {
    api_token: "*******",
    search: { topic },
    limit: "5",
  };

  fetch(
    `https://api.thenewsapi.com/v1/news/all?api_token=*******&search=${topic}&limit=5`,
    requestOptions
  )
    .then((response) => response.json())
    .then((result) => {
      topNews[index] = result.value;
      checkNewsDone();
    })
    .catch((error) => console.log("error", error));
}

function checkNewsDone() {
  numOfCompleted++;
  $("#results").append(`<p>Loading ${numOfCompleted} of 5</p>`);
  if (numOfCompleted === 5) {
    renderData();
  }
}

function renderData() {
  console.log(topNews[0]);
  let html = "";
  for (let i = 0; i < twitterTrends.length; i++) {
    html += "<section class='news'>";
    html += `<h2>${twitterTrends[i]}</h2>`;
    html += "<ul class='articles'>";
    for (let j = 0; j < topNews[i].length; j++) {
      html += `<li>
        ${
          topNews[i][j].image && topNews[i][j].image.thumbnail
            ? `<div class="thumbnail" style="background-image:url('${topNews[i][j].image.thumbnail.contentUrl}')"></div>`
            : ""
        }
        <h3><a href="${topNews[i][j].url}" target="_blank">${
        topNews[i][j].name
      }</a></h3>
        <p>${topNews[i][j].description}</p>
      </li>`;
    }
    html += "</ul></section>";
  }
  html +=
    "<button type='button' class='js-restart button'>Refresh Results</button>";
  $("#results").html(html);
}

function showTrends() {
  let html = "";
  html += "<section class='twitter'>";
  html += "<ul class='trends'>";
  for (let i = 0; i < 5; i++) {
    html += `<li>${twitterTrends[i]}</li>`;
  }
  html += "</ul></section>";
  $(".topFiveTrends").html(html);
}

function getAgain() {
  $("#results").on("click", ".js-restart", function () {
    $("#results").html("");
    twitterTrends = [];
    topNews = [];
    numOfCompleted = 0;
    getTrends();
  });
}

function watchStart() {
  getTrends();
  $(".js-startButton").on("click", function (event) {
    $(".startPage").addClass("hidden");
    $(".topFiveTrends").addClass("hidden");
    $(".startButton").addClass("hidden");
    $("#results").removeClass("hidden");
  });
}

$(watchStart);
$(getAgain);
gmacerola
  • 57
  • 1
  • 7
  • Does this answer your question? [How to append something to an array?](https://stackoverflow.com/questions/351409/how-to-append-something-to-an-array) – imvain2 Jan 19 '21 at 23:08
  • Is `result` or `result.value` already an array (since you're specifying a `limit` I would assume it returns more than one)? – Zac Anger Jan 19 '21 at 23:11
  • 1
    Please provide [mre]. There is no topNews initialisation, neither push in the code above – Vega Jan 19 '21 at 23:23
  • Your question is about the topNews array and logging it. You don't show either of those pieces of code. Being as specific as possible will help get to better answers in the future. – Andy Ray Jan 19 '21 at 23:23
  • I fixed most of it but for some reason, I am trying to do to limit the nested loop in the `renderData` function with `j < topNews[i].data[j].length` and I keep getting undefined. Any ideas? – gmacerola Jan 20 '21 at 16:56

1 Answers1

0

You don't show us the code where you log the array, which is where the issue lies. You also don't show us how topNews is defined.

You're console logging long before the .then() finishes. To get the value, you have to chain another .then() to wait for it.

If you're console logging outside the function, return the entire promise with return fetch(...).then..., and get the value with:

getNews(...).then(() => { /* now you have access to the full topNews array */ });

Andy Ray
  • 30,372
  • 14
  • 101
  • 138