Accessing an object in a returned promise using fetch w / response 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)) } 

What returns this in the console:

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

proto [[PromiseStatus]]: "allowed"

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

I need to access the name / value pairs in an object, but I cannot get to them. I assume that I need to take another step after converting the response to json, but I can not understand. If someone could help, that would be very grateful!

+6
source share
2 answers

response.json() returns a promise, so you also need to process it accordingly, for example:

 .then(function(response) { return response.json(); }) .then(function(parsedData) { // data here }) 
+10
source

Here's an even shorter way to handle json objects

 fetch(endpoint, request) .then(response => response.json()) .then(json => { //handle json response } 
+3
source

All Articles