0

I want to display the news with categories using API. So I'm trying to use await fetch with several variables but it doesn't work. any idea to fix?

const API_KEY = "api key";
const HEADLINES_NEWS =
  "https://newsapi.org/v2/top-headlines?country=us&apiKey=";
const GENERAL_NEWS =
  "https://newsapi.org/v2/top-headlines?country=us&category=general&apiKey=";
const BUSINESS_NEWS =
  "https://newsapi.org/v2/top-headlines?country=us&category=business&apiKey=";
const SPORTS_NEWS =
  "https://newsapi.org/v2/top-headlines?country=us&category=sports&apiKey=";
const ENTERTAINMENT_NEWS =
  "https://newsapi.org/v2/top-headlines?country=us&category=entertainment&apiKey=";
const TECHNOLOGY_NEWS =
  "https://newsapi.org/v2/top-headlines?country=us&category=technology&pageSize=8&apiKey=";
const SEARCH_NEWS = "https://newsapi.org/v2/everything?q=";

This part makes error.

  const response = await fetch([  
    GENERAL_NEWS + API_KEY,
    BUSINESS_NEWS + API_KEY,
    SPORTS_NEWS + API_KEY,
    TECHNOLOGY_NEWS + API_KEY,
    ENTERTAINMENT_NEWS + API_KEY,
  ]);

newsDataArr = [];
  if (response.status >= 200 && response.status < 300) {
    const myJson = await response.json();
    newsDataArr = myJson.articles;
  } else {
    // handle errors
    console.log(response.status, response.statusText);
    newsdetails.innerHTML = "<h5>No data found.</h5>";
    return;
  }

  displayNews();
};
NeNaD
  • 18,172
  • 8
  • 47
  • 89
Austn Yang
  • 79
  • 4

1 Answers1

0

You can not specify multiple endpoints for fetch() directly. Instead, you can wrap all calls separately with Promise.allSettled and send them in the same time:

const results = await Promise.allSettled([
  fetch(GENERAL_NEWS + API_KEY),
  fetch(BUSINESS_NEWS + API_KEY),
  fetch(SPORTS_NEWS  + API_KEY),
  fetch(TECHNOLOGY_NEWS + API_KEY),
  fetch(ENTERTAINMENT_NEWS + API_KEY),
]);
NeNaD
  • 18,172
  • 8
  • 47
  • 89