Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

224
Visualizações
how to prevent firebase to show one message multiple time

I am using firebase to chat messaging. Where when I submit the form for sent messages, all messages are repeated and fetched from start to beginning. Here see a image below to better understanding. enter image description here

Here is the code what i am actually doing.

user_chats.onSnapshot((querySnapshot) => {
            querySnapshot.forEach(doc => {
                user_messages.push(doc.data());
            });
            showMessages();
        });
function showMessages()
    {
        for (let i =0;i<user_messages.length;i++)
        {
            let user_id = user_messages[i].user_id;
            if (user_id == auth_id)
            {
                let selector = $('#my_msg .row');
                selector.find('.chat').text(user_messages[i].message);
                selector.clone().appendTo('.msg_area_div');
            }
            else{
                let selector = $('#user_msg .row');
                selector.find('.chat').text(user_messages[i].message);
                selector.clone().appendTo('.msg_area_div');
            }
        }
    }

Here I want to show the only new items which is pushed not all the older message Help me solve this problem. TIA

Edited

After using the solution of @Frank van Puffelen

function fetchMessage() {
            let document_id = documentID();

        let table = db.collection("chat").doc(document_id).collection('chats');
        let user_chats = table.orderBy('created_at');

        user_chats.onSnapshot((querySnapshot) => {
            querySnapshot.docChanges().forEach(change => {
                if (change.type === "added") {
                    user_messages.push(change.doc.data());
                }
            });
            showMessages();
        });
    }
    function showMessages() {
        $('.msg_area_div').empty();
        for (let i = 0; i < user_messages.length; i++) {
            let active_user_id = user_messages[i].user_id;

            if (active_user_id == auth_id) {
                let selector = $('#my_msg .row');
                selector.find('.chat').text(user_messages[i].message);
                selector.clone().appendTo('.msg_area_div');
            } else {
                let selector = $('#user_msg .row');
                selector.find('.chat').text(user_messages[i].message);
                selector.clone().appendTo('.msg_area_div');
            }
        }
        scrollDown();
    }

got the result like these enter image description here

about 4 years ago · Juan Pablo Isaza
1 Respostas
Responde à pergunta

0

Since you're looping over the QuerySnapshot itself, you're always seeing all documents inside your loop - even if there was only a single change to the snapshot.

This is a valid option, but it means you'll need to clear-and-rebuild the entire chat node each time your onSnapshot gets called. You can do this by clearing the HTML in your showMessages by clearing .msg_area_div before adding the messages with:

$('.msg_area_div').empty();

Alternatively, you can use the lower-level properties to process only the documents that were added, changed or deleted with:

snapshot.docChanges().forEach((change) => {
    if (change.type === "added") {
        console.log("New city: ", change.doc.data());
    }
    if (change.type === "modified") {
        console.log("Modified city: ", change.doc.data());
    }
    if (change.type === "removed") {
        console.log("Removed city: ", change.doc.data());
    }
});
about 4 years ago · Juan Pablo Isaza Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda