MessageForm
//message 입력하는 정보 받아올때
const handleKeyDown = ()=>{
if(content){
typingRef.child(chatRoom.id).child(user.uid).set(user.displayName)
} else {
typingRef.child(chatRoom.id).child(user.uid).remove();
}
}
MainPanel
componentDidMount() {
const { chatRoom } = this.props;
if (chatRoom) {
this.addMessageListeners(chatRoom.id)
this.addTypingListeners(chatRoom.id)
}
}
componentWillUnmount(){
this.state.messagesRef.off()
this.removeListeners(this.state.listenerLists)
}
removeListeners = (listeners)=>{
listeners.forEach(listner=>{
listner.ref.child(listner.id).off(listner.event)
})
}
addTypingListeners=(chatRoomId)=>{
let typingUsers = [];
this.state.typingRef.child(chatRoomId).on("child_added",
DataSnapshot=>{
if(DataSnapshot.key !== this.props.user.uid){
typingUsers = typingUsers.concat({
id:DataSnapshot.key,
name:DataSnapshot.val()
});
this.setState({typingUsers})
}
})
this.addToListenerLists(chatRoomId,this.state.typingRef,"child_added")
this.state.typingRef.child(chatRoomId).on("child_removed",
DataSnapshot=>{
const index = typingUsers.findIndex(user=>user.id===DataSnapshot.key);
if(index!==-1){
typingUsers.filter(user=>user.id!==DataSnapshot.key);
this.setState({typingUsers})
}
}
)
this.addToListenerLists(chatRoomId,this.state.typingRef,"child_removed")
}
addToListenerLists=(id,ref,event)=>{
//이미 등록된 리스너인지 확인
const index = this.state.listenerLists.findIndex(listener=>{
return (
listener.id===id&&
listener.ref===ref&&
listener.event===event
);
})
if(index===-1){
const newListener = {id,ref,event}
this.setState({
listenerLists:this.state.listenerLists.concat(newListener)
})
}
}