I am new to working with javascript APIs. I found a news article API that houses an array of 100 objects. I am trying to create an event listener, that then 'clicked', will generate specific information pulled from the api, such as: article title, author, link, description.
I have successfully fetched the data from the api and my code pulls the desired information from the array of objects, however, It seems to ONLY pull information from the final object. from what I have read, the code is looping through all of the objects quickly and stopping at the final value.
But what I want is to loop through each article with every button click. currently, when I click, the code stops at the final value. each click does not pull any other article.
const searchBtn = document.getElementById('generate');
searchBtn.addEventListener('click', function () {
result.innerHTML = '';
var url =
'https://newsapi.org/v2/everything?' +
'q=Apple&' +
'from=2022-08-15&' +
'sortBy=popularity&' +
'apiKey=xxxxx';
var req = new Request(url);
fetch(req)
.then((response) => response.json())
.then((data) => {
const articleData = Object.values(data.articles);
articleData.forEach((article) => {
result.innerHTML = `
<div class"result-header">
<h1>${article.title}</h1>
<p> <span>Author:</span> ${article.author}</p>
<p>${article.source.name}</p>
</div>
<div class"result-content">
<p> Description: ${article.description}</p>
<p>${article.content} <a href="${article.url}">Click here for full article</a></p>
</div>
`;
});
});
});
* {
box-sizing: border-box;
margin: 0;
padding: 0;
}
body {
background-color: #fefbf6;
font-family: sans-serif;
display: flex;
flex-direction: column;
align-items: center;
justify-content: flex-start;
overflow: hidden;
height: 100vh;
}
#generate {
width: 25rem;
height: 7rem;
margin-top: 12rem;
font-size: 2.5rem;
padding: 2rem 3rem;
background-color: #7f5283;
color: #fefbf6;
border-radius: 2rem;
}
#result {
background-color: #a6d1e6;
width: 80vw;
height: 50vh;
overflow-y: scroll;
margin-top: 2rem;
padding: 2rem 3rem;
}
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta http-equiv="X-UA-Compatible" content="IE=edge" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Document</title>
<link rel="stylesheet" href="style.css" />
</head>
<body>
<button id="generate">New Article</button>
<div id="result"></div>
<script src="script.js" defer></script>
</body>
</html>
This is my first post on here and I hope I was descriptive enough. please let me know if there is anything else to clarify!
thank you in advance