Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Fetch in React Native Expo app

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.

like image 740
Sam Avatar asked Sep 14 '25 15:09

Sam


1 Answers

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

like image 67
Pritish Vaidya Avatar answered Sep 16 '25 16:09

Pritish Vaidya