Juan Pablo
Juan Pablo

Reputation: 13

How to display all JSON Fetch API content on a HTML table using JavaScript

I'm starting to learn JavaScript, and i am having some difficulties for displaying the whole data i got from Json PlaceHolder fake API on my html table. Using the code below i just manage to display the last element from the API itself, and not all elements as i wanted.

Can someone help me figure it out how should i actually do?

There's the code:

fetch('https://jsonplaceholder.typicode.com/posts')
  .then((response) => response.json())
  .then((json) => json.forEach(tableElements)
  )

  function tableElements (element, index, arr){
    arr[index] = document.querySelector('#posts-table tbody').innerHTML = 
    `<td>${element.userId}</td>
    <td>${element.id}</td>
    <td>${element.title}</td>
    <td>${element.body}</td>`
  }

Upvotes: 1

Views: 2271

Answers (1)

Rawand
Rawand

Reputation: 443

Your code is showing one data because when the loop goes it are overwrites the previous one when it loop through the json, change the opperand to += and wrap the table columns with rows <tr>... </tr>
Try this code here

fetch('https://jsonplaceholder.typicode.com/posts')
  .then((response) => response.json())
  .then((json) => json.forEach(tableElements)
  )

  function tableElements (element, index, arr){
    arr[index] = document.querySelector('#posts-table tbody').innerHTML +=
    `<tr>
        <td>${element.userId}</td>
        <td>${element.id}</td>
        <td>${element.title}</td>
        <td>${element.body}</td>
    </tr>`
  }

Upvotes: 1

Related Questions