I'm stuck with Firebase. I have added firebase^4.8.0 to my ionic project and am implementing a live chat. I send the data from the sent message as follows.
send(){
this.datasend = {
'sender': this.sessionData.mobile,
'sendTo': this.data.id,
'message': this.chatt,
}
this.chatt = '';
firebase.database().ref('chats').push(this.datasend).then(res => {
// logic here
});
}
So far so good. I'm using the mobile number as the ID and when I send the data, I forward the message, the sender's mobile number and the recipient's mobile number. This works perfectly.
But I need to recover this data. I only need to show messages to the agent and recipient. I need to know how to make a filter for this.
I'm starting Firebase.
I'm currently stuck on this part.
getmessages() {
this.ref.on('value', data => {
let tmp = [];
date.forEach (date => {
tmp.push ({
'sender': data.val(). sender,
'sendTo': data.val(). sendTo,
'message': data.val(). message,
})
});
this.messagesList = tmp;
});
}
I just need to bring messages from the respective chat. Any suggestions for a filter or other way to store messages that would help me solve this problem please.
I have created a CHAT_ID using the user id's of the respective users.
Suppose there are two users with ID's: 20 & 4, So i have created a chat id using these user ID's after sorting them Math.min(20,4).
const getMessages = () => {
const CHAT_ID = Math.min(currentUser.id, otherUser.id)
const chatref =
firebase.database().ref(`/chats/${CHAT_ID.toString()}`);
chatref.off('value');
chatref.on('value', chatsSnap => {
const chatsArray = snapshotToArrayObject(chatsSnap);
setStorage(`chats_${chatRoom.current}`, chatsArray);
setChatMessages(chatsArray);
scrollToRecentMessage();
markAsRead();
});
}
And When sending the message:
const sendMessage = () => {
const messageArray = {
to: otherUser.id,
from: currentUser.id,
message: newMessage,
messageSeen: false,
timeStamp: new Date()
};
const CHAT_ID = Math.min(currentUser.id, otherUser.id)
firebase.database().ref(`/chats/${CHAT_ID.toString()}`)
.push(messageArray);
}
Hope this might help you