Reputation: 75
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
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
Reputation: 200
You should
getPosts()
, loadData()
and getTemplate()
an async
functionreturn await getPosts()
loadData()
you await getTemplate()
Upvotes: 0
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