2

I am using React Native with firebase (without Redux or anything similar). I have a FlatList listening to changes with firebase by using the 'on' method. The FlatList ist listening to changes but when new Data gets rendered it renders the new data and the old data aswell. So I have the old data and then the old the data with the new data attached.

I retrieve the data like this:

firebase.database().ref(`/thisThat/${uid}/arguments/this/`).orderByChild('timestamp')
      .on('value', (snapshot) => {
        snapshot.forEach((child) => {
            thisArr.push(child.val());
        });
      this.setState({ thisArguments: thisArr });
    });

I am doing it this way because I want it to be ordered (source: https://stackoverflow.com/a/33897213/5075510)

My FlatList looks like this:

<FlatList
  data={this.state.thisArguments}
  renderItem={this.renderItem}
  keyExtractor={(item, index) => index}
  ListEmptyComponent={this.emptyList}
  extraData={this.state}
 />

I think it propably has to do with the way I am retrieving the data. When I am doing it without the forEach everything works fine but it won't render ordered. Thank you in advance for your help!

Frank van Puffelen
  • 565,676
  • 79
  • 828
  • 807
Zander
  • 402
  • 1
  • 4
  • 17
  • 1
    I don't know too much about Firebase but you are `push`ing all the data into `thisArr` every time you handle the event, which explains why data keeps getting appended. I think you need to reset the array before pushing, ie `thisArr = []`. – Aaron Beall Jan 29 '18 at 14:19
  • Yes that fixed the issue. Thank you very much for your comment! – Zander Jan 29 '18 at 14:34

1 Answers1

3

you need to clear thisArr before you push new items to it

firebase.database().ref(`/thisThat/${uid}/arguments/this/`).orderByChild('timestamp')
.on('value', (snapshot) => 
{
    thisArr = [];   // <----- here is the fix
    snapshot.forEach((child) => 
    {
        thisArr.push(child.val());
    });

    this.setState({ thisArguments: thisArr });
});
Ali Faris
  • 17,754
  • 10
  • 45
  • 70