console.log returning "Undefined" no then (fetch)

Asked

Viewed 85 times

-1

I am beginner, apparently the "code" is inside an id, n know how to capture...

const url = 'https://economia.awesomeapi.com.br/json/USD-BRL/'

fetch(url)
.then(resposta => resposta.json())
.then(dados => console.log(dados.code))

1 answer

0


If you access the url in the browser, you will get the following answer:

[
   {
      "code":"USD",
      "codein":"BRL",
      "name":"Dólar Comercial",
      "high":"5.3861",
      "low":"5.3861",
      "varBid":"0.0003",
      "pctChange":"0.01",
      "bid":"5.3858",
      "ask":"5.3864",
      "timestamp":"1604957402",
      "create_date":"2020-11-09 19:00:03"
   }
]

That is, the [ indicates that it is an array, so you need to access the index, for example dados[0]. I added a command to the example for, so that if there is more than one item in the answer, let’s go through each one (for that, I used the property length, which returns the size of the array):

const url = 'https://economia.awesomeapi.com.br/json/USD-BRL/'

fetch(url)
.then(resposta => 
   resposta.json())
.then(dados => {
  for(i=0; i<dados.length; i++) {
    console.log(dados[i].code);
    console.log(dados[i].name);
  }
})

  • Thanks, but now I came up with another doubt, how can I store this result in a variable?

  • @Hérberttavares, the simple answer to this question is: don’t "store" (at least not in the way you seem to try to do). Never try to "take out" an "inside" value from a Promise (or a chain of promises). By doing so, you are going against the asynchronous nature of Javascript. Additional details are given in How to assign the result of a Promise to a variable?.

  • dados is already a variable with everything, what more need? if you need to pass it out of the method that returns from Promise, need to create a variable outside the scope outside of this method, or the most common is to use this in html, to display for example, and this can do in the method itself using the variable dados

Browser other questions tagged

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