Sonia
Sonia

Reputation: 123

listen for changes firebase react native

I want to display the number of likes. How can I listen & display the value change ?

In the firebase doc, they say to use .on('value', function (snap)). But how to implement it ? Should I create a new function ? What about state ? Thank you so much !

class WordItem extends Component {

constructor(props) {
super(props);
this.onPressIcon = this.onPressIcon.bind(this);
this.state = {
  dataSource: new ListView.DataSource({
  rowHasChanged: (row1, row2) => row1 !== row2,
    }),
  }
}



onPressIcon(word){

                var config = {
                apiKey: "",
                authDomain: "",
                databaseURL: ""
                };

                    var ref = firebase.database().ref();

                    let childItem = word+"/likes";
                    console.log(childItem, "childItem")

                    var likes_words = ref.child("items").child(word).child("likes");


                    likes_words.transaction(function(currentLike) {
                        return currentLike + 1;
                        });

            // Sync Object Changes
            likes_words.on('value', function (snap){
              ???
            });

  }

Upvotes: 0

Views: 1234

Answers (1)

sohamdodia
sohamdodia

Reputation: 377

likes_words.on('value', snapshot => {
      value_of_likes = snapshot.val() 
});

Here in value_of_likes you will get you total likes, you can the dispatch action if you are using redux or you can call any other function to update your state

Upvotes: 1

Related Questions