Home > Blockchain >  Display the searching from API
Display the searching from API

Time:12-09

I am trying to display some pictures from a newsAPI from the value of my input field. I am able to display single news, but it dosent change when i search. I know i need to connect the two function, but i dont know how.

const apiKey = "xxxx"; //API Key


input.addEventListener("keyup", function (e)  {
  e.preventDefault();
  if (e.keyCode === 13) {
    let input = document.getElementById("input");
    searchNews(input.value).then((data) => {
      //display the news on the page with the help of the template literal
      console.log(data);
    });
};
});

const searchNews = async (input) => {
  const response = await fetch(
    `https://newsapi.org/v2/everything?q=${input}&apiKey=${apiKey}`
  );
  const data = await response.json();
  return data;
};


const displayNews = async () => {
const news = await searchNews();
 bigNews.innerHTML = `
<div >
<div">
<img id="bigNewsImg" src="${news.articles[0].urlToImage}" 
 
alt="..."> 
<button onclick="favoriteArticle(id)" 
id="${news.articles[0].title}">Save</button>
  </div>
<div >
<div >${news.articles[0].title}</div>
<a id="${news.articles[0].url}" onclick="userArticles(id)" 
target="_blank" 
href="`${news.articles[0].url}" >Read more</a>`
  </div>
</div>
  `; 
};

displayNews();

CodePudding user response:

You're calling displayNews outside the callback that will return the results for you. Your code should be modified to the following:

input.addEventListener("keyup", function (e)  {
  if (e.keyCode === 13) {
    let input = document.getElementById("input");
    searchNews(input.value).then((data) => {
      //display the news on the page with the help of the template literal
      // console.log(data);
      displayNews(data)
    });
  };
});

const searchNews = async (input) => {
  const response = await fetch(
    `https://newsapi.org/v2/everything?q=${input}&apiKey=${apiKey}`
  );
  const data = await response.json();
  return data;
};


const displayNews = (data) => {
  // const bigNews = document.getElementById('big-news'); // or whatever you need to get the news container
 bigNews.innerHTML = `
<div >
<div>
<img id="bigNewsImg" src="${news.articles[0].urlToImage}" 
 
alt="..."> 
<button onclick="favoriteArticle(id)" 
id="${news.articles[0].title}">Save</button>
  </div>
<div >
<div >${news.articles[0].title}</div>
<a id="${news.articles[0].url}" onclick="userArticles(id)" 
target="_blank" 
href="`${news.articles[0].url}" >Read more</a>`
  </div>
</div>
  `; 
};

You also don't need to preventDefault on keyup as it has no effect.

  • Related