I'm learning react-native, and I'm running into an issue. Why does getting data on return from an async function return a promise, but in the async function itself, it correctly returns an array of objects?
On componentDidMount()
, I call my async function which in turn does a fetch to an api url:
componentDidMount() {
let data = this.getData();
console.log(data); // <-- Promise {_40: 0, _65: 0, _55: null, _72: null}
this.setState({
dataSource:this.state.dataSource.cloneWithRows(data),
})
}
async getData() {
const response = await fetch("http://10.0.2.2:3000/users", {
method: 'GET',
headers: {
'Accept': 'application/json',
'Content-Type': 'application/json',
}
});
const json = await response.json();
console.log(json); // <-- (5) [Object, Object, Object, Object, Object]
return json;
}
In console.log(json)
, I get the correct list of json objects, and I can access them with json[0].name
. But later, console.log(data)
returns a promise with odd data:
Promise {_40: 0, _65: 0, _55: null, _72: null}
... and I can no longer find my json objects. Why is this? More importantly, how can I retrieve my json data in componentDidMount()
so that I can set it as the dataSource
?
async
functions return promises.await
magically "unwraps" that promise.let data = this.getData();
doesn't (and cannot use)await
, so you have to handle the promise the "normal" way. If you are not familiar with promises I recommend to read developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/… (this has nothing to do with react native btw, that's JavaScript). – Sage