I cannot access the data using the fetch API

Asked

Viewed 395 times

0

I have a URL that returns data in JSON:

[
  {
    "id": 21,
    "solicitante": "Joao",
    "chamado": "coisa aqui no lab"
  },
  {
    "id": 22,
    "solicitante": "Maria",
    "chamado": "projetor deu pau"
  }
]

On another page, on the same domain, I try to use the API fetch to request the data:

fetch("http://" + window.location.host + "/list/", {method: 'GET'})
.then(function(res){
    console.log(res.json())
    res.map(function(item){
        console.log(item)
    });
});

However, the console.log(res.json()) prints the following:

Promise {<resolved>: Array(2)}
 __proto__: Promise
 [[PromiseStatus]]: "resolved"
 [[PromiseValue]]: Array(2)
   0: {id: 21, solicitante: "Joao", chamado: "coisa aqui no lab"}
   1: {id: 22, solicitante: "Maria", chamado: "projetor deu pau"}
  length: 2
   __proto__: Array(0)

And when I try to use the Array.prototype.map, get this error:

Uncaught (in promise) TypeError: res.map is not a function
    at <anonymous>:4:6

As disassembled above, I am unable to access the answer data.

1 answer

6


Your problem is that Body.json returns a Promise, but you are not waiting for your resolution to use it. This causes you to print on the console to Promise in itself, and not its solved value.

Just as fetch, Body.json also returns a Promise. Thus, you need to wait for the resolution of the two Promises to use the data itself. Below is an example that accesses the Github API:

const GITHUB_API = 'https://api.github.com/users'
const GITHUB_USERNAME = 'lffg'

fetch(`${GITHUB_API}/${GITHUB_USERNAME}`)
  .then((body) => body.json()) // Note aqui que `Body.json` também retorna uma Promise.
  .then((data) => {
    // Aqui já temos as duas promesas resolvidas.
    // Você pode usar os dados como desejar. :)
 
    console.log(`O usuário ${data.login} tem ${data.public_repos} repositórios.`)
  })

Note that you can also use async / await if you prefer:

const GITHUB_API = 'https://api.github.com/users'
const GITHUB_USERNAME = 'lffg'

async function main() {
  // O "await" espera a resolução da Promise:
  const body = await fetch(`${GITHUB_API}/${GITHUB_USERNAME}`)
  // Assim como o `fetch`, também temos que esperar a 
  // resolução da Promise. Por isso, usamos o "await":
  const data = await body.json()
  
  console.log(`O usuário ${data.login} tem ${data.public_repos} repositórios.`)
}

main()

Reference:

Browser other questions tagged

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