Home > Net >  Firebase onSnapshot: Unsubscribe from listening for all users except the one who made the changes
Firebase onSnapshot: Unsubscribe from listening for all users except the one who made the changes

Time:04-09

I'm using react js to deal with firebase.

correct me If I'm wrong please :

  • suppose there are 1000 users on the same page and they are all listening to the collection changes. if one of them, let's say gave one like to a post then all the 1000 users will make a read request to firebase? (not financially friendly).

  • What I want to achieve: just listen to changes for the user who made the modifications to the collection and unsubscribe from listening for others, they will only see changes if they reload the page.

is it possible to implement such this logic with firebase? thanks in advance

CodePudding user response:

For your use-case, you shouldn't use Firestore listener. You should instead get the data once with useEffect and only update the component using setState() when the user liked a post. See sample code below:

const [value, setValue] = useState([])

const colRef = query(collection(db, "<collection>"))

// This will only get collection documents once.
// Needs to refresh/reload page to get updated data.
useEffect(() => {
  const getDataOnce = async () => {
    const querySnapshot = await getDocs(colRef);
    renderData(querySnapshot)
  }
  getDataOnce()
}, [])

// Handles the click button which updates the state.
// Renders updated value to only user who triggered this async function.
async function handleClick() {
  // Document reference to be updated.
  const docRef = doc(db, "<collection>", "<document-id>")
  // Updates the document reference.
  await updateDoc(docRef, {
      like: increment(1)
  })
  // Get the new updated data from the collection.
  const querySnapshot = await getDocs(colRef)
  // Sets the data to the `setValue` state.
  renderData(querySnapshot)
}

// Sets the data to the setValue state.
function renderData(querySnapshot) {
  setValue(querySnapshot.docs.map(doc => ({
    id: doc.id,
    data: doc.data()
  })))
}

The sample code above will only get the updated data for specific user who made the modification. Other users will have to reload/refresh the page to get the updated data. I also left some comments on the sample code.


For more relevant information, you may check out these documentation:

  • Related