Skip to content

Commit 09948b4

Browse files
created function to make an API call
1 parent fc61b22 commit 09948b4

File tree

1 file changed

+35
-0
lines changed

1 file changed

+35
-0
lines changed

fetch/script.js

Lines changed: 35 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,35 @@
1+
async function fetchLatestXKCD() {
2+
const apiEndpoint = 'https://xkcd.now.sh/?comic=latest';
3+
4+
try {
5+
const response = await fetch(apiEndpoint);
6+
if (!response.ok) {
7+
throw new Error(`Fetching error! Status: ${response.status}`);
8+
}
9+
10+
const data = await response.json();
11+
console.log('Received data:', data);
12+
13+
if (data.img) {
14+
const imgElement = document.createElement('img');
15+
imgElement.src = data.img;
16+
imgElement.alt = data.alt || 'XKCD Comic';
17+
18+
const container = document.getElementById('image-container');
19+
container.innerHTML = '';
20+
container.appendChild(imgElement);
21+
} else {
22+
console.warn('No "img" property found in the data.');
23+
}
24+
25+
} catch (error) {
26+
console.error('Error fetching data:', error);
27+
const errorMsg = document.createElement('div');
28+
errorMsg.className = 'error';
29+
errorMsg.textContent = `Error fetching data: ${error.message}`;
30+
document.body.appendChild(errorMsg);
31+
}
32+
}
33+
34+
fetchLatestXKCD();
35+

0 commit comments

Comments
 (0)