I want to automatically fetch new incoming messages from a firestore collection using onSnapshot. While I can set the state inside the callback, I cannot read it.
const [messages, setMessages] = useState(null);
const [chat, setChat] = useState(props.chatId);
useEffect(() => {
const q = query(collection(db, "messages"), where("chat_id", "==", chat), orderBy("date","desc"), limit(5));
// Create the DB listener
const unsuscribe = onSnapshot(q, (querySnapshot) => {
console.log(messages);
if(messages === null){
console.log("setting messages the first time");
setMessages(querySnapshot.docs)
}else{
console.log("updating messages");
setMessages([...querySnapshot.docs, ...messages])
}
});
return () => {
console.log("unsubscribe");
unsuscribe();
}
}, [chat]);
Whenever onSnapshot
fires, messages
is always null
but setMessages
works since the messages are displayed. I tried so many approaches but I could not get it to work.
Help much appreciated.