Reputation: 711
Hi I'm new to firebase and was trying to develop a chat app everything looks ok for the processing of the chat message except that it duplicates the data on the sender's panel as soon as a user switch to pm a different user and after he/she goes back to the previous user it also duplicates the chat for that person too.. although it doesn't store on the firebase database which is also weird.. the duplicate starts from 1 then after that it increments if the user switches to other user/s again
Here is the whole firebase code for the chat app this is the combination of presence and the chat tutorial I just did a small modification on it and I dont know which of the script is causing this duplicate
// Reference for tbl message
var messagesRef = new Firebase('https://url-for-tablemessage');
// Reference for tbl userprofile
var userListRef = new Firebase("https://url-for-userprofile");
var myUser = userListRef.child(idf);
// Get a reference to my own presence status.
var connectedRef = new Firebase("https://url-for-userprofile//.info/connected");
function getmsg(){
// Loads Previous Message with the selected user/s.
messageList.html("");
messagesRef.limit(10).on('child_added', function (snapshot) {
//GET DATA
var data = snapshot.val(), username = data.name, message = data.text,
sendr = data.sender, recievr = data.reciever, ui = $('#chat-avatar').attr("data-ui"),
style_c = "";
if (username != nameField){ style_c = "message chat";}
else{ style_c = "message user"; }
var messageElement = $('<div class="'+style_c+'"><div class="message-info">'+
'<img width="40" height="40" src="temp/user/'+username+'.jpg">' +
'<div class="message-timestamp">' +
' <time datetime="" class="timeago uk-text-small">09:22 am</time>' +
'</div></div>' +
' <div class="message-data">' +
' <div class="bubble"></div></div></div>');
if (((idf == sendr) && (ui == recievr) )||((idf == recievr) && (ui == sendr) )){
messageElement.find('.bubble').html(message).emoji();
//ADD MESSAGE
messageList.append(messageElement);}
//SCROLL TO BOTTOM OF MESSAGE LIST
messageList[0].scrollTop = messageList[0].scrollHeight;
});
}
// A helper function to let us set our own state.
function setUserStatus(status) {
// Set our status in the list of online users.
currentStatus = status;
myUser.set({ id:idf, names: name, firstname:fname, lastname:lname, status: status });
}
function getMessageId(snapshot) {
return snapshot.name().replace(/[^a-z0-9\-\_]/gi,'');
}
// Update our GUI to show someone"s online status.
userListRef.on("child_added", function(snapshot) {
var user = snapshot.val();
if (user.names != name) {
$("<a />")
.attr({"id": getMessageId(snapshot),"data-username":user.names,"data-fname":user.firstname,"data-lname":user.lastname})
.html(user.names + "<br />")
.appendTo("#presenceDiv")
.click(function(){
var dt = $(this).attr("data-username"),df=$(this).attr("data-fname"),dl=$(this).attr("data-lname"),
src="temp/user/"+dt+".jpg";
$('#chat-avatar').show();
$('#chat-avatar').attr({'src':src,"data-os":user.status,"data-ui":user.id})
$('#chat-name').html(df + " " + dl);
console.log(dt);
messageList.html("");
getmsg();
});
$("<li />")
.attr({"id": getMessageId(snapshot),"data-username":user.names,"class":"offcanvas-chat-avatar","data-fname":user.firstname,"data-lname":user.lastname})
.html("<small id='ofstat' data-os="+user.status+" data-ui="+user.id+" ></small><img width='40' height='40' src='temp/user/"+user.names+".jpg'>"+ user.names )
.appendTo("#clist")
.click(function(){
var dt = $(this).attr("data-username"),df=$(this).attr("data-fname"),dl=$(this).attr("data-lname"),
src="temp/user/"+dt+".jpg";
$('#chat-avatar').show();
$('#chat-avatar').attr({'src':src,"data-os":user.status,"data-ui":user.id});
$('#chat-name').html(df + " " + dl);
console.log(dt);
messageList.html("");
getmsg();
});
}
});
// LISTEN FOR KEYPRESS EVENT
messageField.keypress(function (e) {
if (e.keyCode == 13) {
//FIELD VALUES
//messageList.html("");
var username = nameField;
var message = messageField.val();
var ui = $('#chat-avatar').attr("data-ui");
if(message != ""){
//SAVE DATA TO FIREBASE AND EMPTY FIELD
messagesRef.push({name:username, text:message, sender:idf, reciever:ui});
}else{
alert("Text Field Empty");
}
//getmsg();
messageField.val('');
e.preventDefault();
// return false;
}
});
I really need this to get on working.. been stuck here for almost 3weeks now I'm not sure if what I'm doing is actually correct because of this but what I can say is that I think the error lies on the getmsg() function not sure though... Please help me :(
Upvotes: 0
Views: 947
Reputation: 51
Are you trying to format the messages differently when they're from the currently authenticated user? Is that why getMsg() is being called?
I'll offer you another way of thinking about it, as it's something I've managed to do, and I don't have this error. I think your error is coming form the fact that .on('child_added') might be called regardless of whether you call getMsg() or not.
My solution involves the following
messagesRef.limit(msgLimit).on('child_added', function (snapshot) {
var message = snapshot.val();
//format timestamp from linux epoch to readable format
var ts = getTimestamp(message.timestamp);
//gets the image from the user who sent the message
var userImg = userSnapshot.child(message.userID).child('img').val();
//variables for message layout
var chatMsgImg = $('<img>',{class:'avatar', src:userImg});
var chatMsgDiv = $('<div/>',{class:'message'});
var chatMsgArrow = $('<span/>', {class:'arrow'});
var chatMsgName = $('<span/>', {class:'name'}).text(message.from);
var chatMsgTimestamp = $('<span/>', {class:'datetime'}).text(' '+ts);
var chatMsgContent = $('<span/>', {class:'body'}).text(message.text);
//if the message is from the currently signed in user, then align right and use class out
if((message.userID) == userID){
var msg = $('<li/>', {class:'out'});
msg.append(chatMsgImg);
chatMsgDiv.append(chatMsgArrow);
chatMsgDiv.append(chatMsgName);
chatMsgDiv.append(chatMsgTimestamp);
chatMsgDiv.append(chatMsgContent);
msg.append(chatMsgDiv);
msg.appendTo($('#chatDiv'));
}
//otherwise align left and use class in
else{
var msg = $('<li/>', {class:'in'});
msg.append(chatMsgImg);
chatMsgDiv.append(chatMsgArrow);
chatMsgDiv.append(chatMsgName);
chatMsgDiv.append(chatMsgTimestamp);
chatMsgDiv.append(chatMsgContent);
msg.append(chatMsgDiv);
msg.appendTo($('#chatDiv'));
}
$('#chatDiv')[0].scrollTop = $('#chatDiv')[0].scrollHeight;
});
By doing it this way, I still get the message details just the same, but I leave the formatting up to CSS simply using in and out or incoming and outgoing messages (from other users, and from the current user, respectively)
Upvotes: 1