Reputation: 603
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!
Upvotes: 16
Views: 32416
Reputation: 901
just use await:
response = await response.json();
and you will have the object in the response, sure you have to set the function to async first like
async getUserData(){....}
and use await before the fetch too.
Upvotes: 0
Reputation: 1416
Here's an even shorter way to handle json objects
fetch(endpoint, request)
.then(response => response.json())
.then(json => {
//handle json response
}
Upvotes: 8
Reputation: 254926
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
})
Upvotes: 22