简体   繁体   中英

React Native FlatList API Error when no more data to fetch

The following code runs fetchData which pulls data from my API and displays it in a flatlist. When I scroll down the flatlist the API loads page 2, then page 3, etc with infinite pagination, this works perfect. However, when I get to the end of my API data I get this error: TypeError: Invalid attempt to spread non-iterable instance and it's a fatal error.

fetchData = async () => {
    const response  = await fetch(
    'MYAPI&page=' + this.state.postalCode);
    const json = await response.json();
    this.setState(state => ({
     data: [...state.data, ...json]
   }));
 };

handleMore = () => {
 this.setState(state => ({ page: this.state.page + 1 }), () => this.fetchData());
};

  render() {

    return (
<View>

      <FlatList
        data={this.state.data}
        onEndReached={this.handleMore}
        onEndThreshold={0}
        renderItem={({ item }) =>

<Text>{item.id} - {item.title}</Text>

     }
      keyExtractor={item => item.id} />

</View>
    );
  }
}

check if the api is returning a empty array []

or you can do like this:

fetchData = async () => {
  const response  = await fetch(
  'MYAPI&page=' + this.state.postalCode);
  const json = await response.json();
  this.setState(state => ({
    data: [...state.data, ...(json || [])]
  }));
};

I think it comes from you try to use spread operation on your json object while this object is null or undefined. To avoid this problem just adding a condition for checking before you call setState method.

const json = await response.json();
if (json !== undefined && json !== null) {
   this.setState(state => ({
      data: [...state.data, ...json]
    }));
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM