Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

70
Views
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
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!