Skip to content

Commit

Permalink
Fetching APIs are completed
Browse files Browse the repository at this point in the history
  • Loading branch information
kunalarya873 committed Jan 25, 2024
1 parent e7c9bd3 commit a696c91
Show file tree
Hide file tree
Showing 2 changed files with 40 additions and 0 deletions.
3 changes: 3 additions & 0 deletions JS by Shradha Mam/Fetch API/index.html
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,9 @@
<title>Fetch API</title>
</head>
<body>
<button id="btn">Click me</button>
<p id="fact"></p>

<script src = 'script.js'></script>
</body>
</html>
37 changes: 37 additions & 0 deletions JS by Shradha Mam/Fetch API/script.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,37 @@
const URL = "https://cat-fact.herokuapp.com/facts";
const factPara = document.querySelector("#fact");
const btn = document.querySelector("#btn")

const getFacts = async () => {
console.log("Getting data");
try {
const response = await fetch(URL);
if (!response.ok) {
throw new Error(`HTTP error! status: ${response.status}`);
}
const data = await response.json();
if (data.length < 5) {
console.error("The data array has less than five elements");
return;
}
for (let i = 0; i < 5; i++) {
factPara.innerHTML = `${factPara.innerHTML}<p>${i+1}. ${data[i].text}</p>`;
}
} catch (error) {
console.error("Error fetching data:", error);
}
};

function getFacts_byPromise() {
fetch(URL)
.then((response) =>{
return response.json();
})
.then((data) => {
console.log(data);
factPara.innerText = data[2].text;
})
}

btn.addEventListener("click", getFacts_byPromise())
btn.addEventListener('click', getFacts);

0 comments on commit a696c91

Please sign in to comment.