forked from HackYourFuture/Assignments
-
Notifications
You must be signed in to change notification settings - Fork 7
Expand file tree
/
Copy pathindex.js
More file actions
67 lines (57 loc) · 1.94 KB
/
index.js
File metadata and controls
67 lines (57 loc) · 1.94 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
/*
Full description at:https://github.com/HackYourFuture/Assignments/blob/main/3-UsingAPIs/Week2/README.md#exercise-6-using-the-browser-debugger
*/
async function getData(url) {
const response = await fetch(url);
return response.json();
}
function createAndAppend(name, parent, options = {}) {
const elem = document.createElement(name);
parent.appendChild(elem);
Object.entries(options).forEach(([key, value]) => {
if (key === 'text') {
elem.textContent = value;
} else {
elem.setAttribute(key, value);
}
});
return elem;
}
function addTableRow(table, label, value) {
const tr = createAndAppend('tr', table);
createAndAppend('th', tr, { text: label });
createAndAppend('td', tr, { text: value });
}
function renderLaureate(ul, { knownName, birth, death }) {
const li = createAndAppend('li', ul);
const table = createAndAppend('table', li);
const name = knownName?.en ?? '(unknown)';
const birthPlace =
typeof birth?.place?.locationString === 'string'
? birth.place.locationString
: birth?.place?.locationString?.en ?? '—';
addTableRow(table, 'Name', name);
addTableRow(table, 'Birth', `${birth?.date ?? '—'}, ${birthPlace}`);
if (death) {
const deathPlace =
typeof death?.place?.locationString === 'string'
? death.place.locationString
: death?.place?.locationString?.en ?? '—';
addTableRow(table, 'Death', `${death?.date ?? '—'}, ${deathPlace}`);
}
}
function renderLaureates(laureates) {
const ul = createAndAppend('ul', document.body);
laureates.forEach((laureate) => renderLaureate(ul, laureate));
}
async function fetchAndRender() {
try {
const { laureates } = await getData(
'https://api.nobelprize.org/2.0/laureates?birthCountry=Netherlands&format=json&csvLang=en'
);
renderLaureates(laureates);
} catch (err) {
console.error(`Something went wrong: ${err.message}`);
}
}
window.addEventListener('load', fetchAndRender);