Uttara Info Tech
Uttara Info Tech

Reputation: 75

Fetch async/await data and them show/return in html

I am new with async/await fetch. Below is my HTML code

  <div id="content">
    <!-- Data will appear here as list -->
  </div>

below is my vanilla JS code

function loadData() {
  const element = document.getElementById("content");
  element.innerHTML = getTemplate();
}

function getTemplate() {
  async function getPosts() {
    try {
      const url = "https://jsonplaceholder.typicode.com/posts";
      const response = await fetch(url);
      console.log(response);

      if (response.ok) {
        const res = await response.json();
        return res;
      } else {
        throw new Error(response.statusText);
      }
    } catch (error) {
      return error;
    }
  }

  getPosts().then(data => console.log(data));

  //How I return data from here so it will update in the DOM

};

loadData();

How show data as list after async/wait fetch my data using vanilla JS.

Upvotes: 1

Views: 7123

Answers (3)

Mario
Mario

Reputation: 4998

If it is not a problem to reorganize the code a bit, try the following. On how to return, remember an asynchronous function returns a promise and you must work in context, so I get the promise of the response to call getPosts and with the data I get the template that I then give in #content

function loadData() {
  const element = document.querySelector("div#content");

  getPosts().then(posts => {
    const template = getTemplate(posts);

    element.innerHTML = template;
  });
}

async function getPosts() {
  const url = "https://jsonplaceholder.typicode.com/posts";
  const response = await fetch(url);

  return await response.json();
}

function getTemplate(posts) {
  const rows = posts.map(postToRowView).join("");

  return `<table>
    <thead>
      <tr>
        <th>Title</th>
        <th>Body</th>
      </tr>
    </thead>

    <tbody>${rows}</tbody>
  </table>`;
}

function postToRowView(post) {
  return `<t>
    <td>${post.title}</td>
    <td>${post.body}</td>
  </tr>`;
}

loadData();
<div id="content"></div>

Upvotes: 1

siddhesh bhasme
siddhesh bhasme

Reputation: 200

You should

  1. Mark getPosts() , loadData() and getTemplate() an async function
  2. And then just return await getPosts()
  3. Lastly, in loadData() you await getTemplate()

Upvotes: 0

Mirodil
Mirodil

Reputation: 2329

You can do as following:

function loadData() {
  const element = document.getElementById("content");
  getTemplate(element);
}

function getTemplate(element) {
  .....

  getPosts().then(data => {
     console.log(data));
     element.innerHTML = data;
  })
};

Upvotes: 0

Related Questions