Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Accessing object in returned promise using fetch w/ react js

I have this function:

  getUserData() {
    fetch(this.props.apiUrl + this.state.username + '?client_Id=' + this.props.clientId + '&client_secret=' + this.props.clientSecret)
      .then(function(response) {
        var data = response.json();
        this.setState({
          userData: data
        });
        console.log(this.state.userData);
      }.bind(this))
      .catch(function(error) {
        this.setState({
          username: null
        });
        console.log(error)
      }.bind(this)) 
  }

Which returns this in the console:

Promise {[[PromiseStatus]]: "pending", [[PromiseValue]]: undefined}

proto [[PromiseStatus]] : "resolved"

[[PromiseValue]] : Object
avatar_url : "https://avatars.githubusercontent.com/u/"
login      : "hello world"
.
.
.

I need to access the name/value pairs in the object but I can't get to them. I'm assuming I need to take one extra step after I convert the response to json but can't figure it out. If anyone could help it would be greatly appreciated!

like image 810
Banner Avatar asked Aug 03 '16 00:08

Banner


People also ask

How do you get Promise results from Promise object in React JS?

JavaScript gives you two methods of handling the result of a promise, the first being . then(), a function that takes a function as a parameter, which it will pass the resolved value to. const promiseThen = new Promise((resolve, reject) => { setTimeout(() => { resolve('Hi!' ); }, 1000); }); promiseThen .

How do I access data from Promise React?

The most accessible way to fetch data with React is using the Fetch API. The Fetch API is a tool that's built into most modern browsers on the window object ( window. fetch ) and enables us to make HTTP requests very easily using JavaScript promises.

Does fetch return a Promise?

fetch() The global fetch() method starts the process of fetching a resource from the network, returning a promise which is fulfilled once the response is available. The promise resolves to the Response object representing the response to your request.


2 Answers

response.json() returns a promise, so you also need to handle it appropriately, eg:

.then(function(response) {
    return response.json();
})
.then(function(parsedData) {
    // data here
})
like image 119
zerkms Avatar answered Sep 21 '22 07:09

zerkms


Here's an even shorter way to handle json objects

fetch(endpoint, request)
.then(response => response.json())
.then(json => {
  //handle json response
}
like image 26
Jordan Hochstetler Avatar answered Sep 23 '22 07:09

Jordan Hochstetler