Skip to content
Advertisement

dynamically display value from an axios get request using vanilla javascript and dom manipulation

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.

// Get todos Function
function getToDos() {
  // Get request
  axios
    .get("//https:www.apiCall")
    .then((res) => {
      // log response
      console.log(res);
      // user creates todos variable
      if (res.length === 0) {
        console.log("No to-dos addded");
      }
      const todos = res.data;
      displayToDos(todos);
    })
    .catch((err) => {
      console.log(err);
    });
}

// display todos function
function displayToDos(todos) {
  if (todos.length === 0) {
    // Create ul element
    const ul = document.createElement("ul");
  }

  let li = document.createElement("li");
  li.setAttribute("class", "toDoItem");

  for (let i = 0; i < todos.length; i++) {
    // adds text to li element
    let textContent = document.createTextNode("Title: " + todos[i].title);

    // Append content to li
    document.li[i].appendChild("textContent");
    document.ul.appendChild(li[i]);
    document.body.appendChild(ul);
  }
}

getToDos();


Advertisement

Answer

You have lots of errors in your displayToDos method. It should look something like this:

function displayToDos(todos) {
  // You have to create an ul element, not only when there are 0 todos.
  const ul = document.createElement("ul");

  for (let i = 0; i < todos.length; i++) {
    // You need to create an li for each todo
    let li = document.createElement("li");
    li.setAttribute("class", "toDoItem");
    let textContent = document.createTextNode("Title: " + todos[i].title);
    li.appendChild(textContent);

    // And add it to the ul
    ul.appendChild(li);
  }

  // Finally, add the ul to your html page.
  document.body.appendChild(ul);
}

User contributions licensed under: CC BY-SA
3 People found this is helpful
Advertisement