Cli Ad
Cli Ad

Reputation: 103

How can I save user's followers in firebase? React Native

I have two collections in my database one called Buyers and the other called Sellers. Whenever the buyer follows the seller I save the seller's Uid in a subcollection called userFollowings in the Buyers collection.

How can I save the followers Uids too? Save the buyer uid in a subcollection called userFollowers in the Sellers collection every time a buyer follows a seller?

here's my code:


const onFollow = () => {
  firebase.firestore()
      .collection("Buyers")
      .doc(firebase.auth().currentUser.uid)
      .collection("userFollowings")
      .doc(props.route.params.uid)
      .set({})


}
const onUnfollow = () => {
  firebase.firestore()
      .collection("Buyers")
      .doc(firebase.auth().currentUser.uid)
      .collection("userFollowings")
      .doc(props.route.params.uid)
      .delete()
}

Upvotes: 2

Views: 305

Answers (1)

Renaud Tarnec
Renaud Tarnec

Reputation: 83163

You can use a batched write, as follows, in such a way the two writes complete atomically.

  const db = firebase.firestore();

  const onFollow = () => {
    const buyerID = firebase.auth().currentUser.uid;
    const followerID = props.route.params.uid;

    const buyerFollowerRef = db
      .collection('Buyers')
      .doc(buyerID)
      .collection('userFollowings')
      .doc(followerID);

    const sellerFollowerRef = db
      .collection('Sellers')
      .doc(followerID)
      .collection('userFollowers')
      .doc(buyerID);

    const batch = db.batch();
    batch.set(buyerFollowerRef, { foo: 'bar' });
    batch.set(sellerFollowerRef, { foo: 'bar' });
    batch.commit();
  };

For the onUnfollow function, use batch.delete().


You could also use a Cloud Function triggered when the doc in the userFollowings subcollection is created.

This would be the way to go if the end-user does not have the permission to write to the userFollowers subcollection, and therefore cannot execute the above batched write.

Upvotes: 2

Related Questions