0

I am trying to fetch data from an api into console and then display it on a page.

I have correctly fetched the data from the placeholder api into console.log, but I cannot display it onto the page in the div. What am I doing wrong?

fetch('https://jsonplaceholder.typicode.com/todos/1')
  .then(response => response.json())
  .then(json => console.log(json))

document.getElementById("console")
<div id="console"></div>
SavPhill
  • 636
  • 6
  • 24
  • 2
    console.log is for logging in DevTools. It is not a div. – Emil Karlsson Oct 28 '21 at 07:45
  • Thank you. So how can I take the information I have fetched from the API, and display it in page? – SavPhill Oct 28 '21 at 07:46
  • There seems to be some code parts missing. Do you try to add it into the .console div as well? Should be something like `document.getElementById("console").innerHTML = json` ? – Ingo Steinke Oct 28 '21 at 07:47
  • 1
    @IngoSteinke Should probably be `innerText` - we wouldn't want to accidentally introduce an opportunity for XSS – phuzi Oct 28 '21 at 07:49
  • Do you just want to display the object, or do you want to put the data in that object in a table, for example? "display it onto the page in the div" is a little ambiguous. – Andy Oct 28 '21 at 08:11
  • My end goal is to display in a table as you have suggested. @Andy – SavPhill Oct 28 '21 at 08:12

2 Answers2

4

innerHTML could achieve.

fetch('https://jsonplaceholder.typicode.com/todos/1')
  .then(response => response.json())
  .then(json => {
  console.log(json);
  document.getElementById("console").innerHTML += JSON.stringify(json)}
  )
Alan Yu
  • 1,462
  • 12
  • 21
  • 2
    `innerText` may be more appropriate for JSON just in case the JSON contains HTML snippets. Don't want to be adding inadvertant ` – phuzi Oct 28 '21 at 07:48
  • 2
    `+=` on `.innerHTML` [is discouraged](https://stackoverflow.com/questions/11515383/why-is-element-innerhtml-bad-code). – Ivar Oct 28 '21 at 07:49
  • I know the OP has it in their question but `.then(json` should probably be `.then(data` as at that point it's no longer JSON as the JSON has been parsed. Edit: just realised that code is in the examples for jsonplaceholder.typicode.com which isn't great, it's just misleading. – Andy Oct 28 '21 at 07:58
1

If you just want to output the data as a formatted string you could create a function to "pretty print" the stringified data using <pre> and <code>.

const output = document.querySelector('.output');

fetch('https://jsonplaceholder.typicode.com/todos/1')
  .then(response => response.json())
  .then(updateHTML);

function updateHTML(data) {
  const json = JSON.stringify(data, null, 2);
  const html = `<pre><code>${json}</code></pre>`;
  output.insertAdjacentHTML('beforeend', html);
}
<div class="output"></div>

If you wanted to display the data differently (in a table, for example) you could iterate (map) over the keys and values returned by Object.entries to return a string of row HTML, and add that html to the page.

const output = document.querySelector('.output');

fetch('https://jsonplaceholder.typicode.com/todos/1')
  .then(response => response.json())
  .then(updateHTML);

function updateHTML(data) {

  // Get the object entries - and array of key/value pairs
  const entries = Object.entries(data);

  // Iterate over the entries and return a new array
  // of strings created from the key/value using a
  // template string.
  const rows = entries.map(([key, value]) => {
    return `
      <tr>
        <td class="heading">${key}</td>
        <td>${value}</td>
      </tr>
    `;
  });

  // Create a new HTML string by `join`ing up the row array
  // and adding it to a new string
  const html = `<table><tbody>${rows.join('')}</tbody></table>`;

  // Insert the HTML into the page
  output.insertAdjacentHTML('beforeend', html);
}
table { background-color: #efefef; border-collapse: collapse; border: 1px solid #afafaf; }
td { padding: 0.4em; border: 1px solid white; }
.heading { text-transform: uppercase; text-align: right; font-weight: 500; background-color: #dfdfdf; }
<div class="output"></div>

Addition documentation

Andy
  • 61,948
  • 13
  • 68
  • 95