I'm using fetch
in my React Native
app using Expo
. The problem I'm having is that there seems to be an execution of code which throws an error before the promise is resolved. Here's my code:
renderWithData() {
return fetch('https://myapi.com')
.then((response) => response.json())
.then((myListData) => {
return (
<FlatList data={myListData} renderItem={({item}) => <Text>{item.dataItem}</Text>} />
);
})
.catch((error) => {
console.error(error);
});
}
The error I'm getting reads:
Invariant Violation: Objects are not valid as a React child (found: object with keys {_40, _65, _55, _72}). If you meant to render a collection of children, use an array instead.
That's because I seem to be getting some type of object that I think represents the promise. This throws the error. Only a split second later, I get the array from the API call.
The code that invokes renderWithData()
is as follows:
<View style={styles.listContainer}>
{this.renderWithData()}
</View>
How do I get it to wait till the data are received. I thought using then
would do it but clearly it's not working.
The fetch api returns a promise as mentioned in the docs. Therefore you're returning a promise
in your function this.renderWithData()
and not a React Element
You must setState
the data you get from the fetch api
and render it dynamically in the FlatList
as
state = {
myListData: []
}
renderWithData = () => { . //... Ignore if already bound
return fetch('https://myapi.com')
.then((response) => response.json())
.then((myListData) => {
this.setState({myListData}}
})
.catch((error) => {
console.error(error);
});
}
<View style={styles.listContainer}>
<FlatList data={this.state.myListData} renderItem={({item}) => <Text>{item.dataItem}</Text>} />
</View>
Assuming that getPhoneExtensions()
is mentioned as renderWithData()
in the last snippet
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