简体   繁体   中英

How to update FlatList if data is updated

The way I get the data is inside the componentWillMount method, its working fine when it renders the FlatList when the app boots up, but when I'm adding data, all I want is to update also my flatList. How can I do that here's the code snippet:

 componentWillMount() {
    console.log(`componentDidUpdate`, prevProps);
    const user = firebase.auth().currentUser;

    if (user != null) {
      const db = firebase.firestore();
      const docRef = db.collection('userCheckInHistory').doc(user.uid);
      docRef
        .get()
        .then(doc => {
          if (doc.exists) {
            let shopId = this.props.shopId;
            let userShopHistoryData = doc.data();
            let userShopPick = userShopHistoryData[shopId];
              this.setState({
                checkInHistory: userShopPick,
                shopId: this.props.shopId
              });


          } else {
            console.log('No such document!');
            return false;
          }
        })
        .catch(function(error) {
          console.log('Error getting document:', error);
        });
    }
  }

Now this is my FlatList code:

renderHistoryList() {
    const sortedData = Common.getArrayByObject(this.state.checkInHistory);
    if (this.state.checkInHistory !== '') {
      return (
        <FlatList
          data={sortedData}
          extraData={this.state}
          keyExtractor={this._keyExtractor}
          renderItem={({ item }) => (
            <MyListItem
              id={item}
              onPressItem={this._onPressItem}
              selected={!!this.state.selected.get(item)}
              title={item}
            />
          )}
        />
      );
    } else {
      return <Spinner />;
    }
  }

When you get your data from api set your state with that data. And then if you add data and setState, react native will rerender app and you will see your data on the list.

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