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.