Home » Javascript » FlatList rerenders data from Firebase multiple times whenever new data is added

FlatList rerenders data from Firebase multiple times whenever new data is added

Posted by: admin August 19, 2018 Leave a comment

Questions:

I am attempting to build a chat app interface using react native and firebase and am having problems updating the data that is fetched from my database. I can load existing data into the Flatlist I am using fine:

const firebaseApp = firebase.initializeApp(firebaseConfig);
let db = firebaseApp.database();
let ref = db.ref("/room");

 componentDidMount() {
      ref.on('value', function(snapshot) {
        snapshot.forEach(function (childSnapshot){
          childData.push(childSnapshot.val());
        });
        this.setState({
          messages: childData
        });
       messageCount = snapshot.numChildren();
     }.bind(this));
 }

Flatlist Code:

<KeyboardAvoidingView style={styles.inputContainer}>
      <FlatList
          data={this.state.messages}
          // renderItem={({item}) =><Text>{item.contents}</Text>}
          keyExtractor = {item => item.timestamp}
          renderItem={({item}) => <Bubble style={{margin: 10}} 
          color="#FFC800" arrowPosition='right'>{item.contents}</Bubble>}
            />}
        />
        <Button onPress={()=>{this.onPressButton()}} title="Send">Click me</Button>      
      </KeyboardAvoidingView>

This is where I add the text in a text input to the database

function addMessage(messageText) {
  messageCount++;
  firebase.database().ref('room/'+messageCount).set({
      contents: messageText,
      timestamp: firebase.database.ServerValue.TIMESTAMP
  });
}

That code gives me the following result which is what I want (ignore the terrible styling):
enter image description here

But whenever I try to send a message, it gets added to the database correctly, but the flatlist updates to show this:

enter image description here

Where the previous message and the new message are rendered multiple times. What is the best way to render a new item from the database into the flatlist?

Answers: