Search code examples
reactjsionic-frameworkgoogle-cloud-firestorelistener

How do i set up a listener for a firestore document?


I am making a chat with Ionic and react using firestore as my database. I am storing all the messages in an array [] in a document in firestore. And simply want both users to fetch the data again if a message is added. So i basically want to add a listener to my document. My chat is working but you have to reload the page to see new messages... This is my code:

const [chats, setChats] = useState([]);

    db.collection("chats").doc(chatId).onSnapshot((doc) => {

                setChats(doc.data().messages)

            });

I either i get infinite loops or doc.data() is not defined. Is there a good way to fetch data using this function? Or do you need for example firebase cloud functions?


Solution

  • I solved my problem this way:

    const [chats, setChats] = useState([]);
    
    
    useEffect(() => {
    
            db.collection("chats").doc(chatId).onSnapshot(snapshot => {
                updateMessages(snapshot.data())
            })
    
        }, []);
    
    
        function updateMessages(data : any) {
    
            setChats(data.messages);
        }
    

    When i put the listener inside a useEffect() hook i solved the problem with infinite loops since a new listener would start each time the state was updated inside the listener. Now the listener is only initialized once when the component is mounted.

    And by sending snapshot.data() to a function and THEN fetching data.messages i solved the problem with snapshot.data().messages being undefined.