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

72
Visualizações
Infinite loop when attmepting to render a new chat message using react and firebase

Currently working on a chatting app in React and I've run into an issue where whenever I use ref.on('child_added'...) I get an infinte loop. I know this shouldn't be the case since if ref.on will only render something if a child is added to a node. My code is below.

useEffect(()=> {
    //Depending on what user you want to chat with, set the chatroom
    if ((props.who)>(auth.currentUser.uid)) {
      setChatroom(props.who + auth.currentUser.uid);
    } else {
      setChatroom(auth.currentUser.uid + props.who);
    }
    
  let ref = db.ref(`Messages/${chatroom}`);
  //Loop over all the messages and store them in the messages array to display 
  ref.on('value', (snapshot) => {
    let newUserState = [];
    snapshot.forEach(data => {
      newUserState.push(data.val());
    })
    setMessages(newUserState);
  });
},[chatroom,props.who])

let ref = db.ref(`Messages/${chatroom}`);
ref.on('child_added', (snapshot) => {
  setMessages([...messages,snapshot.val()]);
});

The array of messages I work with is what is ultimately rendered at the end. The first useffect statement is used to add all the chat messages with a particualar user upon clicking on the chat with that user (the array's only updated upon choosing to interact with that user). The code below it used to add a message to an array only if the database was updated with a message.

about 4 years ago · Juan Pablo Isaza
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