jennie788
jennie788

Reputation: 456

How do I return data from fetch and display in div?

For example here is the content of a JSON on a remote URL:

{ "title": "The title", "description": "The description" }

Could you please help with this:

The function below displays "[object Promise]" in my DIV.

async buildWidget() {
    var id = "whatever"
    let data = await fetch('getItem.php?id=' + id + '&callback=getJSONP');
    var json = data.json();
    
    return json.title;
}

No JQuery please.

Thanks

Upvotes: 0

Views: 1817

Answers (3)

Salvino D'sa
Salvino D'sa

Reputation: 4506

fetch method returns a promise, so just await and get the JSON response from it. You can then simply get the properties like data.title or data.description and render then to the DOM.

async function buildWidget() {
  const response = await fetch('https://jsonplaceholder.typicode.com/posts/1');
  const data = await response.json();

  document.getElementById('data').innerHTML = data.title;
}

buildWidget();
<div id="data"></div>

Upvotes: 1

Ilijanovic
Ilijanovic

Reputation: 14904

First of all .json() returns an promise and then also needs to await for it.

Second: async functions are asynchronouse they return an promise.

async buildWidget() {
    var id = "whatever"
    let data = await fetch('getItem.php?id=' + id + '&callback=getJSONP');
    var json = await data.json();
    
    return json.title;
}

buildWidget().then(title => {
   console.log(title)
})

Upvotes: 1

matthew2564
matthew2564

Reputation: 41

Use await on .json() as it is asynchronous I.e.

async buildWidget() {
    var id = "whatever"
    let data = await fetch('getItem.php?id=' + id + '&callback=getJSONP');
    var json = await data.json();
    
    return json.title;
}

Upvotes: 2

Related Questions