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!
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 .
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.
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.
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
})
Here's an even shorter way to handle json objects
fetch(endpoint, request)
.then(response => response.json())
.then(json => {
//handle json response
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With