Fetch news from API and populate the pages :
1. Create a fetchNews function in the scripts/function.js
:
anything in this file is accessible across all your pages, So create a fetch function for both of your news pages.
async function fetchNews(url) {
try {
const response = await fetch(url);
if (!response.ok) {
throw new Error('Network response was not ok');
}
const data = await response.json();
return data;
} catch (error) {
console.error('There was a problem with the fetch operation:', error);
}
}
2. Create Logic file for your Home.js
in Logic/Home.js
::
let articlesDiv = document.getElementById("top-news-articles")
import NewsArticle from "../components/NewsArticle/NewsArticle.js"
fetchNews("https://saurav.tech/NewsAPI/top-headlines/category/health/in.json").then(data => {
let articles = data.articles
let newsComponent = ``
for(const news of articles){
let newsItem = NewsArticle(news.title,news.description,news.urlToImage,news.url)
newsComponent = newsComponent + newsItem
}
articlesDiv.innerHTML = newsComponent
});
3. Similarly Create a Logic file for Cnn
page in Logic/Cnn.js
::
let articlesDiv = document.getElementById("cnn-news-articles")
import NewsArticle from "../components/NewsArticle/NewsArticle.js"
fetchNews("https://saurav.tech/NewsAPI/everything/cnn.json").then(data => {
let articles = data.articles
let newsComponent = ``
for(const news of articles){
let newsItem = NewsArticle(news.title,news.description,news.urlToImage,news.url)
newsComponent = newsComponent + newsItem
}
articlesDiv.innerHTML = newsComponent
});
Conclusion
With this we have created simple news app using pre-reactJS. Learn more at Learn