I am trying to use Gifted Chat and firebase Real-time database to have user-to-user chat. On the first screen render I retrieve all the messages from the database. Then when I send a new message to the database the screen re-renders and I will retrieve the messages again, how do I stop this from happening?
Example:
Database {Message1: Hi}
First screen render {Hi}
Send message{ Message2: Hello}
Database {Message1: Hi, Message2:Hello}
Second screen render {Hi, Hello, Hi, Hello, Hi}
useLayoutEffect(() => {
getUser();
// for real time update
const unsubscribe = database()
.ref('100-101/')
.on('value', snapshot => {
console.log(snapshot);
var y = [];
snapshot.forEach(doc => {
y.push({
_id: doc.val()._id,
createdAt: doc.val().createdAt,
text: doc.val().message,
user: user,
});
});
for (var x in y) {
setMessages(previousMessages =>
GiftedChat.append(previousMessages, y[x]),
);
}
});
return () => unsubscribe();
}, []);
const onSend = useCallback((msgs = []) => {
setMessages(previousMessages => GiftedChat.append(previousMessages, msgs));
var time = new Date().getTime();
for (let i = 0; i < msgs.length; i++) {
database().ref('100-101/').push({
_id: msgs[i]._id,
message: msgs[i].text,
user: msgs[i].user.uid,
createdAt: time,
});
}
}, []);