简体   繁体   中英

Update react native listview on child changed event firebase

I am trying to build a react native listview with firebase that automatically updates and re renders the list when data changes.

I run my queries in componentDidMount

async componentDidMount(){

 let userId = await AsyncStorage.getItem('workUserId')

this.chatIdRef.child(userId).orderByChild('timeStamp').on('child_added', snap => {
this.chatsRef.child(snap.key).on('value', snapshot => {
      this.handleEvent("child_added", snap.val().userId, snapshot.val().text, snap.val().userName, snap.key);
  });
});

this.chatIdRef.child(userId).orderByChild('timeStamp').on('child_changed', snap => {
  this.chatsRef.child(snap.key).on('value', snapshot => {
      this.handleEvent("child_changed", snap.val().userId, snapshot.val().text, snap.val().userName, snap.key);
    });
  });
}

And then use a case to either run a child added event or child changed

handleEvent(event, receiverId, text, name, key) {
switch (event) {
case "child_added":
  this.items.push({event: event, receiverId: receiverId, text: text, name: name, key: key})
  this.setState({
    dataSource: this.state.dataSource.cloneWithRows(this.items)
  });
break;

case "child_changed":
  this.items.push({event: event, receiverId: receiverId, text: text, name: name, key: key})
  this.setState({
    dataSource: this.state.dataSource.cloneWithRows(this.items)
  });
break;
}}

When I change data in firebase the listview doesn't update accordingly, it only adds another row. I am not sure if my problem is with react native or optimizing how I run my firebase queries.

It will add new row only, as you have not updated value. You are just pushing element into array so it will add element not update existing one.

You need to change code of case "child_changed" like:

let newArray = oldArray.slice();
newArray[indexToUpdate] = {
  ...oldArray[indexToUpdate],
  field: newValue,
};
let newDataSource = oldDataSource.cloneWithRows(newArray);

You can read more about this from here

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