Gabriel
Gabriel

Reputation: 199

Realtime React Chat with Firestore, how can I subscribe to the data?

Structure

Hey everyone! I'm super lost rn, I gotta make a chat feature on some app and it's hosted on firebase with the current structure, I just have no clue how to subscribe to all the data.

Using react-firebase-hooks, I can subscribe to the chat list easily:

getting list

But then, how can I subscribe to all the messages within? Since, for example, I should be able to get a notification from one chat while I'm on another, I managed to get the messages like this:

enter image description here

But I need to be able to constantly watch all this data

I'm just extremely lost rn, any help would be extremely appreciated, thanks a bunch!

Upvotes: 0

Views: 517

Answers (1)

Luke
Luke

Reputation: 8407

instead of using get you can use onSnapshot

you will need to do that within a effect, so that you can unsubscribe from it.

React.useEffect(() => {
   const unsubscribe = collection.onSnapshot(docs => ...);
   return unsubscribe;
}, [])

https://firebase.google.com/docs/firestore/query-data/listen

update:

note that useCollection is already returning a snapshot, so it might be a better approach to also use useCollection for child listeners. Also note, that in that case you will need to render the child hook into a child component - which will also make your app perform better because if your component gets unmounted, also the child listeners get unsubscribed


const Root = () => {
   const [chats] = useCollection(firestore.collection("chats"));

   return (
      <ul>
        {chats.map(doc => <Child doc={doc} />)
      </ul>
   )
}

const Child = ({ doc }) => {
   const [messages] = useCollection(doc.collection("messages"))
   // ...
}

Upvotes: 2

Related Questions