I thought the code below would do it but it gives me an “TypeError: Cannot read property ‘0’ of undefined”. how can get my data to display? I’m still new to javascript, please keep it simple and easy to understand.
JavaScript
x
45
45
1
// Get todos Function
2
function getToDos() {
3
// Get request
4
axios
5
.get("//https:www.apiCall")
6
.then((res) => {
7
// log response
8
console.log(res);
9
// user creates todos variable
10
if (res.length === 0) {
11
console.log("No to-dos addded");
12
}
13
const todos = res.data;
14
displayToDos(todos);
15
})
16
.catch((err) => {
17
console.log(err);
18
});
19
}
20
21
// display todos function
22
function displayToDos(todos) {
23
if (todos.length === 0) {
24
// Create ul element
25
const ul = document.createElement("ul");
26
}
27
28
let li = document.createElement("li");
29
li.setAttribute("class", "toDoItem");
30
31
for (let i = 0; i < todos.length; i++) {
32
// adds text to li element
33
let textContent = document.createTextNode("Title: " + todos[i].title);
34
35
// Append content to li
36
document.li[i].appendChild("textContent");
37
document.ul.appendChild(li[i]);
38
document.body.appendChild(ul);
39
}
40
}
41
42
getToDos();
43
44
45
Advertisement
Answer
You have lots of errors in your displayToDos method. It should look something like this:
JavaScript
1
20
20
1
function displayToDos(todos) {
2
// You have to create an ul element, not only when there are 0 todos.
3
const ul = document.createElement("ul");
4
5
for (let i = 0; i < todos.length; i++) {
6
// You need to create an li for each todo
7
let li = document.createElement("li");
8
li.setAttribute("class", "toDoItem");
9
let textContent = document.createTextNode("Title: " + todos[i].title);
10
li.appendChild(textContent);
11
12
// And add it to the ul
13
ul.appendChild(li);
14
}
15
16
// Finally, add the ul to your html page.
17
document.body.appendChild(ul);
18
}
19
20