알림
ChatRoom의 아이디는 Datasnapshot의 key
Datasnapshot → 채팅방 만들었을때 이용했던 거
id: 채팅방의 아이디
total : 해당 채팅방 전체 메시지 개수
lastKnownTotal : 이전에 확인한 전체 메시지 개수
count : 알림으로 사용 될 숫자
DataSnapshot.numChildren(): 전체 children 개수 전체 메시지
//state에 notification 추가
state ={
...
notification:[]
}
//listener 추가
addNotificationListener=(chatRoomId)=>{
this.state.messagesRef.child(chatRoomId).on("value",DataSnapshot=>{
if(this.props.chatRoom){
this.handleNotification(
chatRoomId,
this.props.chatRoom.id,
this.state.notifications,
DataSnapshot
)
}
})
}
//handle notification
handleNotification=(chatRoomId,currentChatRoomId,notifications,DataSnapshot)=>{
let lastTotal = 0;
//이미 notifications state 안에 알림 정보가 들어있는 채팅방과 그렇지 않은 채팅방을 나눠주기
let index = notifications.findIndex(notification=>
notification.id===chatRoomId)
//notifications state 안에 해당 채팅방의 알림 정보가 없을때
if(index===-1){
notifications.push({
id: chatRoomId,
total: DataSnapshot.numChildren(),
lastKnownTotal : DataSnapshot.numChildren(),
count:0
})
}
//이미 해당 채팅방의 알림 정보가 있을 때
else{
//상대방이 채팅 보내는 그 해당 채팅방에 있지 않을때
if(chatRoomId!==currentChatRoomId){
//현재까지 유저가 확인한 총 메시지 개수
lastTotal = notifications[index].lastKnownTotal
//count (알림으로 보여줄 숫자)를 구하기
//현재 총 메시지 개수 - 이전에 확인한 총 메시지 개수>0
//현재 총 메시지 개수가 10개이고 이전에 확인한 메시지가 8개 였다면 2개를 알림으로 보여줘야함
if(DataSnapshot.numChildren()- lastTotal>0){
notifications[index].count = DataSnapshot.numChildren()- lastTotal; }
}
//total property에 현재 전체 메시지 개수를 넣어주기
notifications[index].total = DataSnapshot.numChildren();
}
//목표는 방 하나 하나의 맞는 알림 정보를 notifications state에 넣어주기
this.setState({notifications})
}
//notification 정리
clearNotifications=()=>{
let index = this.state.notifications.findIndex(
notification => notification.id === this.props.chatRoom.id
)
if(index !== -1){
let updatedNotifications = [...this.state.notifications];
updatedNotifications[index].lastKnownTotal = this.state.notifications[index].total;
updatedNotifications[index].count =0;
this.setState({notifications:updatedNotifications});
}
}
// get notification
getNotificationCount=(room)=>{
//해당 채팅방의 count 수를 구하는 중입니다.
let count =0;
this.state.notifications.forEach(notification=>{
if(notification.id===room.id){
count =notification.count;
}
})
if(count>0)return count;
}