Search code examples
javascriptes6-promise

Unable to fetch object using Promises


I'm using the new Fetch API to retreive objects from an API. This is my code.

getUserYguid(){
  fetch(this.myapi, {
    credentials: "include",
    method: 'get',
    headers: {
      "Content-type": "application/x-www-form-urlencoded; charset=UTF-8"
    },
    body: null
  }).then(function(response){
    console.log(response.status)
    console.log(response.json());
    let obj = response.text();
    console.log(obj.name);
  }).catch(function(error){
    console.log('Request failed', error);
  });
}

When I call response.status, it works fine and I can see the status message as 200. When I call response.json() or response.text(), i can see the complete object being returned. The problem is that the next line of code doesn't work. When I try to retrieve a property from the object, like

console.log(obj.name);

I get, undefined


Solution

  • response.text() returns a promise so you have to use then one more time

    fetch(url, opts).then(function(response){
      response.text().then(function(txt){
        console.log(txt)
      })
    })
    

    and by the look of your obj.name use it seems like you want a json response... not a text, so you need to do:

    fetch(url, opts).then(function(response){
      response.json().then(function(obj){
        console.log(obj.name)
      })
    })
    

    get is the default method so no need to specify that... and blob is null so there is no need for that either...