0

I am fetching todo list, I am wondering why it gives me undefined when I do this

.then((response) => {
  response.json();
  }

it works with

.then(response => response.json())

Why is this happening?

Also, when I'm fetching the data, they are objects and I save them in array

  completed: true,
  id: 199,
  title: "numquam repellendus a magnam",
  userId: 10
},

etc..

Now, I have html template for this, I'd like to load this in my html where my styles are, how can I do this?

<div class="card">
<p>//Want Id here</p>
<strong>// Want Title here</strong>
</div>

fetching code:

let todos = [];

function fetchData() {
    fetch('https://jsonplaceholder.typicode.com/todos').then(response => response.json())
  .then((json) => {
    todos = json;
    console.log(todos);
  })
  }

fetchData();
AbsoluteBeginner
  • 2,160
  • 3
  • 11
  • 21
Dave
  • 1
  • 1
  • 9
  • 38

2 Answers2

2

Why don't you use template literals?

My suggestion:

let todos = [];

fetchData();

function fetchData() {
  fetch('https://jsonplaceholder.typicode.com/todos')
    .then(response => response.json())
    .then(json => todos = json)
    .then(() => {
      for (let item of todos) {
        toAppend.innerHTML += `
<div class="card">
<p>${item.id}</p>
<h2>${item.title}</h2>
</div>
`;
      }
    });
}
<div id="toAppend"></div>

Anyway, if you only need to show fetched items, an alternative, easier solution can be:

const fetchData = async() => (await fetch('https://jsonplaceholder.typicode.com/todos')).json();

fetchData()
  .then(data => {
    for (let item of data) {
      toAppend.innerHTML += `
<div class="card">
<p>${item.id}</p>
<h2>${item.title}</h2>
</div>
`;
    }
  });
<div id="toAppend"></div>

Here fetchData() is an asynchronous function.

AbsoluteBeginner
  • 2,160
  • 3
  • 11
  • 21
1
.then((response) => {
  response.json();
})

This function above doesn't return anything. It does response.json() but does not return it.

You need to add return so it gets passed to the next .then() :

.then((response) => {
  return response.json();
})

This will work. But ES6 allows a nice syntactic sugar :

.then(response => response.json())

Without the braces, response.json() will be returned, without you having to explicitly write return.

This is the difference between braces and no braces.

But there's an even nicer way to deal with it, using async/await :

let todos = [];

async function fetchData() {
    const response = await fetch('https://jsonplaceholder.typicode.com/todos');
    const todos = await response.json();
    console.log(todos);
}

fetchData();
Jeremy Thille
  • 26,047
  • 12
  • 43
  • 63