Using the fetch api

Asked

Viewed 432 times

0

I am trying to use fetch to consume data from an api, but when trying to access some attributes of the object, it is giving UNDEFINED:

const url = 'https://api.sheety.co/30b6e400-9023-4a15-8e6c-16aa4e3b1e72';

fetch(url)
  .then(response => response.json())
  .then(result => {
    const dados = JSON.stringify(result);
    // console.log(response.name);


    document.getElementById('wrap').innerHTML = dados.name;
  })
  .catch(function(err){
    console.error(err);
  })

How html is being rendered:

inserir a descrição da imagem aqui

1 answer

1


First, you are turning an object into a string, so you cannot access its properties if it has been converted to a string (dados.name for example).

Second, the result is an array, so you need an index (`result[0] for example) or iterate with the object (for, foreach, etc).

const url = 'https://api.sheety.co/30b6e400-9023-4a15-8e6c-16aa4e3b1e72';

fetch(url)
  .then(response => response.json())
  .then(result => {
    const dados = JSON.stringify(result);
    // console.log(response.name);

    // aqui os dados em formato string
    document.getElementById('wrap').innerHTML = dados;
    // aqui o valor de name, como é um array, o valor do primeiro elemento
    document.getElementById('valor').innerHTML = result[0].name;
    // aqui, todos os names:
    result.forEach(function(element) {
       document.getElementById('todosValores').innerHTML += "<img src='" + element.photo + "'>" +  element.name + "<br/>";
    });
    
  })
  .catch(function(err){
    console.error(err);
  })
div {
   border: solid 1px #000;
   display: inline-block;
   margin: 2px;
   padding: 5px;
}

img {
  width: 50px;
  height: 50px
}
<div id="valor">
</div>

<div id="todosValores">
</div>

<div id="wrap">
</div>

  • Need to turn into string?

  • no, I put in the code just to illustrate, the result is ready to be used :)

  • I do a for, why does only one name appear? for(const data of result) { console.log(data.name); Document.getElementById('wrap'). innerHTML = data.name; }

  • see the example I put with foreach

  • Very good, thank you!

Browser other questions tagged

You are not signed in. Login or sign up in order to post.