Skip to content

Instantly share code, notes, and snippets.

@jeanbauer
Created December 23, 2018 02:00
Show Gist options
  • Save jeanbauer/3f14e89bae2486f2302d7a370fb1f8f0 to your computer and use it in GitHub Desktop.
Save jeanbauer/3f14e89bae2486f2302d7a370fb1f8f0 to your computer and use it in GitHub Desktop.
[REQUEST FOR FEEDBACK]: How to subscribe to realtime data using Firebase Collections and React Hooks
// Usage - client:
useEffect(() => {
subscribe('users', setUsers)
subscribe('messages', setMessages)
}
// Subscribe implementation
export function subscribe(collection, onDataReceive) {
db.collection(collection)
.onSnapshot((docs) => {
const data = []
docs.forEach(doc => {
data.push(Object.assign({
id: doc.id,
}, doc.data()))
})
onDataReceive(data)
})
}
@jeanbauer
Copy link
Author

The code above works, my question is: Is there a good pattern to do the same?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment