Blog>
Snippets

Subscribing to Firebase Real-time Updates

Shows how to subscribe to document changes in Firebase's Firestore, specifically listening for real-time updates and reflecting them in the application state.
import { collection, onSnapshot } from 'firebase/firestore';
import { db } from './firebase'; // Assume this is where your Firebase config is
Imports necessary functions from Firebase Firestore and your Firebase config.
const subscribeToRealTimeUpdates = () => {
  const unsubscribe = onSnapshot(collection(db, 'messages'),
    (snapshot) => {
      const messages = snapshot.docs.map(doc => ({...doc.data(), id: doc.id}));
      console.log(messages);
      // Here you would update your application state with the new messages
    },
    (error) => {
      console.error('Error fetching real-time updates:', error);
    }
  );
  return unsubscribe;
};
Defines a function to subscribe to real-time updates on the 'messages' collection. It logs the updated messages or errors.
// To start listening for real-time updates, call the function
// When you want to stop listening, call the unsubscribe function returned by subscribeToRealTimeUpdates
const unsubscribe = subscribeToRealTimeUpdates();
// Call unsubscribe() when you want to stop listening for updates
Shows how to start and stop listening for real-time updates using the subscribeToRealTimeUpdates function.