Home > other >  Render API/Json data using Async Await in Html using javascript
Render API/Json data using Async Await in Html using javascript

Time:09-25

I want to render JSON data in HTML in div with id content in paragraph tags in this format -

ID:XYZ

Username : ABC

Age : Kd

How can I do it ?? I am new in async-await, can someone help me ??

./user.json file

[
{
    "id":1002,
    "username":"dcode",
    "age":30

},

{

"id":1140,
"username":"otheruser",
"age":41
}


]
//My async await 
async function loadUsers()
{
    const response = await fetch("./user.json");
    return response.json();

}

document .addEventListener('DOMContentLoaded',async()=>{
try{
    users = await loadUsers();

}
catch (e)
{
    console.log("ERROR");
    console.log(e);

}

console.log(users);



})

CodePudding user response:

You can't control when your script is going to execute, At times it's possible that DOMContentLoaded was already fired by the time you get a chance to listen for the event.

To take that into consideration, your code needs to check if DOMContentLoaded was already fired and, if so, proceed to execute right away whatever it is that needed to wait for DOMContentLoaded:

Refer this answer

A working example of what you want to achieve.

//My async await
async function loadUsers() {
  let response = await fetch("https://api.sampleapis.com/wines/reds");
  return response.json();
}

let users;

async function runWhenPageIsFullyParsed() {
  console.log("on content load");
  try {
    users = await loadUsers();
  } catch (e) {
    console.log("ERROR");
    console.log(e);
  }

  console.log(users);
}

if (document.readyState === "complete") {
  runWhenPageIsFullyParsed();
} else {
  window.addEventListener("DOMContentLoaded", runWhenPageIsFullyParsed);
}

Note: I have used an external link here for example.

CodePudding user response:

After fetching the data you can create paragraph elements, add user data to the innerText of the paragraph element and then append it to the div container having id content

async function loadUsers() {
  const response = await fetch("./user.json");
  return response.json();
}

document.addEventListener("DOMContentLoaded", async () => {
  try {
    const users = await loadUsers();
    const divContainer = document.getElementById('content');
    users.forEach(user => {
        const paragraphElem = document.createElement('p');
        paragraphElem.innerText = `ID: ${user.id} \n Username: ${user.username} \n Age: ${user.age}`;
        divContainer.appendChild(paragraphElem);
    });
  } catch (e) {
    console.log('ERROR');
    console.log(e);
  }
});
<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Document</title>
</head>
<body>
  <div id="content"></div>
  <script src="script.js"></script>
</body>
</html>
  • Related