0

I am training on the Hacker News API project and I wanted to do it my way, I fetched the API with the following urls and I put a toggle_button function but when I try to put the variable data in this function nothing is displayed I do not know what is the problem can someone guide me?

Here's my HTML CODE:

<!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">
    <link rel="stylesheet" href="css/style.css">
    <title>ClonerNews</title>
</head>
<body>
    <h2>Welcome To <span>ClonerNews</span> !</h2>
    <div id="main">
        <button id="liveData" class="category" onclick="toggleButton('liveData');">Live Data</button>
        <button id="topstories" class="category" onclick="toggleButton('topstories');">Top Stories</button>
        <button id="stories" class="category" onclick="toggleButton('stories');">Stories</button>
        <button id="jobs" class="category" onclick="toggleButton('jobs');">Jobs</button>
        <button id="polls" class="category" onclick="toggleButton('polls');">Polls</button>
    </div>
    <div id="result"></div>
    <span id="span_txt" style="color: aliceblue;"></span>
</body>
<script src="script.js"></script>
</html>

And here's my script.js

//url of news api
var topStoriesUrl = "https://hacker-news.firebaseio.com/v0/topstories.json";

//url of particular news item
var newItemUrl = "https://hacker-news.firebaseio.com/v0/item/";

let result = document.getElementById("result"); seront affichées.


//fetch data
const fetchData = (url) => {
    return new Promise((resolve, reject) => {
        fetch(url)
        .then((res) => res.json())
        .then((data) => resolve(data))
        .catch((err) => reject(err));

    }); 
};

//show data
const showData = async () => {
    var data = await fetchData(topStoriesUrl);
    console.log(data);
    data.map(async (d) => {
        let newsData = await fetchData(`${newItemUrl}${d}.
        json`);
        console.log(newsData);
    });
};
showData();

const liveData = getElementById("liveData");
const stories = getElementById("stories");
const jobs = getElementById("jobs");
const polls = getElementById("polls");

function toggleButton() {
    var span = document.getElementById("span_txt");
    if(span.innerHTML != "") {
      span.innerHTML = "";
    } else {
      span.innerHTML = data
    }
}
Alain
  • 1
  • 1
  • You've implemented the [explicit promise construction antipattern](https://stackoverflow.com/q/23803743/283366). Don't do that – Phil Feb 02 '22 at 07:12
  • You also have a newline and a bunch of spaces between `.` and `json` in your second `fetchData()` URL and a random `seront affichées.`. I suggest you use your browser's dev-tools for spotting errors like this – Phil Feb 02 '22 at 07:14
  • Okey I''ll try to fix it thank you ! – Alain Feb 02 '22 at 07:14

0 Answers0