'Count unread messages using firebase and react js
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)
Solution 1:[1]
Split your code into two separate useEffects. 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]);
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Henrik Erstad |
