Search code examples
firebasegoogle-cloud-platformgoogle-cloud-firestore

How to listen to button triggers using Firebase


I have two clients and I'm looking for a way to send a button click on one client and listen to the other client.

It is possible to detect data changes using Cloud Firestore's onSnapshot(). However, this is a little different from what I'm looking for. What I'm asking for is to send something that can identify multiple buttons (for example, button A, and button B).

Cloud Firestore sends data in units of documents, so a huge number of "number of users * number of buttons" is required.

Is there a way to listen to less complex data such as buttons?


Solution

  • I'm looking for a way to send a button click on one client and listen on the other client.

    If you have two clients, both having a button and you want to track when each one is clicking their button, then you have to create a connection between these two clients. So please see below a possible database schema in Firestore:

    db
    |
    --- connections (collection)
         |
         --- docId (document)
              |
              --- userOneEmail: [email protected]
              |
              --- userTwoEmail: [email protected]
              |
              --- userOneButtonClick: false
              |
              --- userTwoButtonClick: false
    

    In the above schema, both userOneButtonClick and userTwoButtonClick hold the value of false. This means that none of the clients clicked the button. As soon as one of the clients clicks the button, you have to change the value of the client from false to true. To find the document with a particular connection you have to create a query that looks like this:

    db.collection("connections").whereEqualTo("userOneEmail", [email protected])
                                .whereEqualTo("userTwoEmail", [email protected])
    

    Now you have to attach a real-time listener to the above query and track the values of userOneButtonClick and userTwoButtonClick.