When I click on my button, I expect the data from the endpoint to be returned.
However, I get this error:
JavaScript
x
3
1
Id:undefinedURL:undefinedName:undefinedDescription:undefined
2
3
This is my function:
JavaScript
1
23
23
1
//fetch
2
function RetrieveEntries(){
3
fetch("http://vk-data:8003/v1/entries/", {
4
headers:{
5
'x_auth': 'gdjsjaosh-hkds-dhjsk-hjjdbah',
6
'data': 'access-control',
7
}}
8
)
9
.then(function(response) {
10
return response.json()
11
})
12
.then((response) => {
13
var results = document.getElementById('results')
14
console.log(response)
15
response.forEach(element => {
16
results.innerHTML = 'Id:' + response.id + 'Type:' + response.type + "Name:" + response.name "<br><br>"
17
18
});
19
})
20
.catch(error => console.error(error))
21
22
}
23
Advertisement
Answer
You’re replacing the innerHTML
in every iteration. Did you mean to append to it?
You should also be using the properties from each element iteration. Trying to access them on response
(an array) is why you get undefined
values.
To format the results, you might want to use something like a <dl>
which can be styled easily with CSS.
JavaScript
1
26
26
1
const createElement = (tag, content) => {
2
const el = document.createElement(tag);
3
el.append(content);
4
return el;
5
};
6
7
const formatData = ({ id, url, name, description }) =>
8
createElement(
9
"dl",
10
createElement(
11
"div",
12
createElement("dt", "Id"),
13
createElement("dd", id)
14
),
15
createElement(
16
"div",
17
createElement("dt", "URL"),
18
createElement("dd", Object.assign(createElement("a", url), { href: url }))
19
),
20
createElement(
21
"div",
22
createElement("dt", "Description"),
23
createElement("dd", description)
24
)
25
);
26
Then fetch your data, map the array to the formatted elements and append them to the results div…
JavaScript
1
22
22
1
const results = document.getElementById("results");
2
// empty the <div> for a fresh start
3
results.innerHTML = "";
4
5
fetch("http://vk-data:8003/v1/entries/", {
6
headers: {
7
x_auth: "gdjsjaosh-hkds-dhjsk-hjjdbah",
8
data: "access-control",
9
},
10
})
11
.then((res) => (res.ok ? res.json() : Promise.reject(res)))
12
.then((data) => {
13
results.append(
14
data.flatMap((entry) => [
15
formatData(entry),
16
document.createElement("br"),
17
document.createElement("br"), // could also just use CSS margin
18
])
19
);
20
})
21
.catch(console.error);
22