javascript - firebase child added action triggers multiple times when react navigation back button clicked -
i have weird problem. have component listing comments of specific movie. triggers firebase on(child_added) in componentwillmount. , when child added, add item reducer array. works perfect. codes that:
main component:
class ... extends .... { render () { return () { <comments ...props /> <comment /> // button pops modal when click } } }
comments component:
class comments extends component { ..... componentwillmount() { this.props.fetchmoviecomments(this.props.movie.id); } ...... render () { // listing array of comments. no problem in here } }
fetchmoviecomments action:
export function fetchmoviecomments(id) { console.log('tattaaaa'); const ref = firebase.database().ref(`comments/${id}`); return (dispatch) => { ref.on('child_added', (snapshot) => { console.log('aaaaaa'); const commentdata = snapshot.val(); commentdata.uid = snapshot.key; const userref = firebase.database().ref(`users/${snapshot.val().userid}`); userref.once('value', (snap) => { console.log('bbbb'); commentdata.name = snap.val().name; dispatch({ type: inject_movie_comment, payload: commentdata }); }).catch(err => console.log(err)); dispatch({ type: fetch_movie_comments, payload: snapshot.val() }); }); ref.on('child_removed', (snapshot) => { const removedid = snapshot.key; dispatch({ type: remove_comment, payload: removedid }); }); }; }
when child added triggered, fetch username of comment in it. there no problem here also.
for example, searched movie , lot of movies listed. choose 1 of them, , commented movie. there no problem comment appears in list, when click button (react navigation) , go movie again , add comment, adds comment twice. not database. adds firebase database 1 time child_added listener triggers 2 times. logs console 2 times: 'aaaaaa' , adds last added child array 2 times.
guess what? if make 5 times , forward, , comment, last comment appears 5 times. lol. added database 1 time, child_added triggers 5 times.
as said, used react navigation. how can solve problem? make wrong choice trigger fetching comments in componentwillmount?
Comments
Post a Comment