Im building a web chat app using next js and firebase.How can i implement an unread message counter?Im using a boolean field called read inside my message doc to check if a message is read or not.
I tried using useEffect but it seems that my counter is just increasing without stoping.
const [notification,SetNotification]=useState(0)
const[messages,SetMessages]=useState([])
useEffect(()=>{
const getMessages=async ()=>{
const data=await getDocs(lastMessageRef)
SetMessages(data.docs.map((doc)=>({...doc.data(), id:doc.id})))
};
getMessages();
messages.forEach((message)=>{
if(message.read==false){
SetNotification(notification 1)
}
})
},[messages])
console.log(notification)
CodePudding user response:
Split your code into two separate useEffect
s. Also, using SetNotifaction
inside a loop will cause a lot of problems. I suggest using Array.filter
instead.
const [notification,SetNotification] = useState(0)
const [messages,SetMessages] = useState([])
useEffect(() => {
const getMessages = async () => {
const data = await getDocs(lastMessageRef)
SetMessages(data.docs.map((doc) => ({...doc.data(), id:doc.id})))
};
getMessages();
}, [messages]);
useEffect(() => {
const unreadMessages = messages.filter(message => message.read === false)
SetNotification(unreadMessages.length)
}, [messages]);