skip to Main Content

I am looking to GET Data from API and display in HTML page using JavaScript fetch function.
The JavaScript codes are detailed below. I can read the console.log of the user data from API. However, nothing is displayed on the HTML page as expected.


    <script>
      fetch('https://dummyjson.com/user')
        .then(response => response.json())
        .then(data => console.log(data));
    </script>

I can’t seem to figure out what is missing.

Screenshot 1: Data API

I have added a loop function to retrieve and filter the API data and insert the result into HTML tag as detailed below:

    <script>
      fetch('https://dummyjson.com/user')
        .then(result => {
          return result.json();
        })
        .then(data => console.log(data))
        .then(data => {
          data.forEach(user => {
            const show = `<p>${user.firstName}</p>`;
            let html = document.querySelector('item');
            html.insertAdjacentHTML('after begin', show);
          });
        });
    </script>

Screenshot 2: Console.log results

Expected result should have been the first names (firstName) of all the user.

When the code runs, output does not display the expected result in the HTML page.
The console log does not show any errors. Simply a blank page.

Complete Code Below:


<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <style>
          body {
        background: transparent;
        color: #2c0493;
        padding: 44px;
        margin: 0;
        height: 100vh;
        align-items: center;
        font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, Oxygen,
          Ubuntu, Cantarell, 'Open Sans', 'Helvetica Neue', sans-serif;
      }

      h3,
      h2 {
        margin: 0;
      }
    </style>
  </head>
  <body>
    <h2 id="header">GET Data from API</h2>
    <h3>And display in HTML with JavaScript</h3>
    <hr />
    <div id="item"></div>
    <script>
      fetch('https://dummyjson.com/user')
        .then(result => {
          return result.json()
        })
        .then(data => console.log(data))
        .then(data => {
          data.forEach(user => {
            const show = `<p>${user.firstName}</p>`
            let html = document.querySelector('item')
            html.insertAdjacentHTML('afterbegin', show)
          });
        });
    </script>
  </body>
</html>

More Screenshots here:

Screenshot 3: No HTML output

Expected output:

Screenshot 4: Expected output

3

Answers


  1. According to the querySelector() documentation:

    The Document method querySelector() returns the first Element within
    the document that matches the specified CSS selector, or group of CSS
    selectors. If no matches are found, null is returned.
    Blockquote

    https://developer.mozilla.org/en-US/docs/Web/API/Document/querySelector

    You can use getElementById() to achieve the desired result with something like

    let html = document.getElementById("item");
    html.innerHTML = "<p>whatever you want<p>"
    

    https://developer.mozilla.org/en-US/docs/Web/API/Document/getElementById

    Login or Signup to reply.
  2. You do array foreach but not on the correct array.

    should be something like:

    fetch('https://dummyjson.com/user')
      .then(result => {
        return result.json()
      })
      .then(data => console.log(data))
      .then(data => {
        data.users.forEach(user => {
          const show = `<p>${user.firstName}</p>`
          let html = document.querySelector('item')
          html.insertAdjacentHTML('afterbegin', show)
        });
      });
    
    Login or Signup to reply.
  3. There seems to be a bit of misunderstanding regarding the .then method.

    When .then is called, it immediately returns a new Promise object in a pending state.

    It’s important to note that the callback attached to this .then method depends on the state of the preceding Promise in the chain. The callback will only execute once the preceding Promise has been resolved.

    (Obviously, because we can’t access the resolved value if the task hasn’t been completed yet.)

    Once the preceding Promise is resolved, the callback executes and returns the value we instructed it to return.

    So what happens next? That returned value is passed to the next .then method’s callback.

    How does this work?

    As mentioned earlier, .then always returns a new Promise, which starts in a pending state. When the callback function within the .then gets executed, this new Promise resolves with the value returned by the callback.

    In your case, the first callback returns a JSON object.

    However, the second callback isn’t returning any value because you’re using () => console.log(data). This is implicitly saying () => return console.log(data), and console.log() returns undefined.

    As a result, the value passed to the third .then is undefined, not the JSON you intended to work with.

    One more thing I want to point out is a typo in your .querySelector('item'). You need to correct it to .querySelector('#item'), as you’re selecting an element by its ID, and IDs are referenced with a # in querySelector.

    so you can either do

    fetch('https://dummyjson.com/user')
            .then(result => {
              return result.json()
            })
            .then(data => console.log(data); return data)
            .then(data => {
              data.forEach(user => {
                const show = `<p>${user.firstName}</p>`
                let html = document.querySelector('#item')
                html.insertAdjacentHTML('afterbegin', show)
              });
            });

    or

    fetch('https://dummyjson.com/user')
            .then(result => {
              console.log(data);
              return result.json()
            })
            .then(data => {
              data.forEach(user => {
                const show = `<p>${user.firstName}</p>`
                let html = document.querySelector('#item')
                html.insertAdjacentHTML('afterbegin', show)
              });
            });
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search