skip to Main Content

I am trying to get data from a free APi : API URL

I then want to push the full response into a div on my page.
I can consolelog it fine, my solution is not working.
This is what i have tried.

async function fetchData() {
    fetch('https://jsonplaceholder.typicode.com/posts/1/comments')
  .then((response) => response.json())
  .then((json) => console.log(json));
    i = json;
    console.log(i);
    document.getElementById('matcher').innerHTML = i.toString();
}

2

Answers


  1. As it is an array, try to render it using map.
    Try:

    json?.map((item, index) => document.getElementById('matcher').innerHTML = item?.title;
    

    or, if you want an output in your procedure for a while, then

    document.getElementById('matcher').innerHTML = json[0].body;
    

    Moreover, you can use innerText instead of innerHTML render a value of some property.

    Login or Signup to reply.
  2. async function fetchData() {
        fetch('https://jsonplaceholder.typicode.com/posts/1/comments').then(function (response) {
        // The API call was successful!
        return response.json();
    }).then(function (data) {
        // This is the JSON from our response
        console.log(data);
        document.getElementById('matcher').innerHTML = data[0].body;
    }).catch(function (err) {
        // There was an error
        console.warn('Something went wrong.', err);
    });
    }
    

    OR you can use JSON.stringify

    async function fetchData() {
        fetch('https://jsonplaceholder.typicode.com/posts/1/comments').then(function (response) {
        // The API call was successful!
        return response.json();
    }).then(function (data) {
        // This is the JSON from our response
        console.log(data);
        data = JSON.stringify(data);
        document.getElementById('matcher').innerHTML = data;
    }).catch(function (err) {
        // There was an error
        console.warn('Something went wrong.', err);
    });
    }
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search