Update a Firestore field if there have been no changes for 5 minutes

I am currently displaying cards that contain data from Google Firestore. One of the fields in these cards is "Status", which can be remotely turned on and off from outside the app. I want the Status to automatically switch to "Off" after 5 minutes or if there are no updates to the document within 5 minutes.

This functionality is essential in case a user loses connection and is unable to send the "Status: Off" message. I don't want the card to remain stuck at "On" forever.

Although I'm using Vue.js, I've experimented with different approaches but haven't been able to achieve this successfully. I apologize if this question would be better suited for another platform, as I couldn't find any relevant solutions while researching.

To help visualize my issue, here are some screenshots:

https://i.sstatic.net/XytV5.png

https://i.sstatic.net/PUYOo.png

https://i.sstatic.net/cJ71V.png


<div >
    <div class="ma-4">
        <div centered class="text-lg-center headline"> 
            Live Middleware Status 
            <p v-bind="allig">{{ seconds }}</p>
        </div>
    </div>

        <v-card slow v-bind="allig" :class="`mx-4 my-4 ${user.Status}`" v-for="user in users" :key="user.id">
          <v-card-title flat class="pa-n3">
            <v-flex class="mx-auto" xs6 sm4 md2 lg2>
              <div class="caption grey--text">Location Site ID</div>
              <div class="title">{{user.id}}</div>
            </v-flex>
            <v-flex class="mr-auto " xs6 sm4 md2 lg2>
              <div class="caption grey--text">ID</div>
              <div class=" ml-n12 title">{{user.CustomerID}}</div>
            </v-flex>
            <v-flex style :class="`mx-auto ${user.Status}`" xs6 sm4 md2 lg2>
              <div class="caption grey--text">Current Status</div>
              <div class="status title mx-2">{{user.Status}}</div>
            </v-flex>
            <v-flex style class="mx-auto caption green--text" xs6 sm4 md2 lg2>
              <div class="caption grey--text">Last Message</div>
              <div class="Green my-2 title">{{user.TimeStamp}}</div>
            </v-flex>
          </v-card-title>
        </v-card>

      </div>
      </template>


      <script>
// eslint-disable-next-line
import firestore from "firestore";
// eslint-disable-next-line
import db from "@/components/fbInit";
import firebase from "firebase";

export default {
  // eslint-disable-next-line
  components: { },
  data() {
    return {
      wide: false,
      ToggleDelete: false,
      card: true,
      light: true,

      seconds: "",

      users: [],

      links: [{ route: "/logs" }]

    };
  },

  created() {

    var user = firebase.auth().currentUser;
    var employeeRef = db
      .collection("userProfiles")
      .doc(user.uid)
      .collection("MX")
      .orderBy("TimeStamp", "desc")

    employeeRef.onSnapshot(snap => {
      // eslint-disable-next-line
      console.log(snap.size);
      this.users = [];
      snap.forEach(doc => {
        const data = 
        {
          id: doc.id,
          Name: doc.data().Name,
          GroupHex: doc.data().GroupHex,
          DeviceType: doc.data().DeviceType,
          UserIDInt: doc.data().UserIDInt,
          CustomerID: doc.data().CustomerID,
          SiteID: doc.data().SiteID,
          SuperID: doc.data().SuperID,
          Status: doc.data().Status,
          TimeStamp: doc.data().TimeStamp,
          Original: doc.data().Original
          };
        this.users.push(data);
      });
    });
  },

  methods: {   }

};
</script>



Answer №1

In order to ensure consistent updates, it is important to have a server-side process that periodically checks and modifies documents. One effective approach would be implementing a scheduled Cloud Function. Here is an example of how this could be done:

// functions/index.js

const admin = require('firebase-admin');
admin.initializeApp();
const db = admin.firestore();

exports.updateIdle = functions.pubsub.schedule('* * * * *').onRun(async () => {
  const snap = await db.collection("MX")
    .where("Status", "=", "On")
    .where("Timestamp", "<", admin.firestore.Timestamp.fromMillis(Date.now() - 5 * 60000))
    .get();

  await Promise.all(snap.docs.map(doc => doc.ref.update({Status: 'Off'})));
});

This function will execute every minute, identifying documents with timestamps older than five minutes and changing their status to "Off".

Keep in mind that this is just a sample implementation, and adjustments may be necessary based on your specific requirements.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

The onChildRemoved() method in Firebase Android ChildEventListener is triggered before onChildAdded() when new data is added

When adding new data to Firebase, I am using the following code: updateChildren(childUpdates, new DatabaseReference.CompletionListener() { @Override public void onComplete(DatabaseError databaseError, DatabaseReference databaseReference) ...

What is the best way to display monthly data in a stacked bar chart using Recharts?

My data is structured as follows: [ { "CarbonAmount": 120, "CarbonDescription": null, "Date": "2022-03-14" }, { "CarbonAmount": 140, "CarbonDescription": "Electricity", "Date": "2022-04-11" } ] I am aiming to format it ...

Transferring data using a JavaScript enhanced form

I'm currently working on a search page that showcases results in a table format. I am looking to enhance the functionality using Javascript. The table is contained within a form, and each row offers multiple actions, such as adding a comment. While I ...

Guide to positioning a div in the center while implementing animations through transition and transformation using scale

Creating a popup for my React app without relying on external libraries is my current project. I am experimenting with using transition and transform with scale to size the popup dynamically based on screen size and content, then center it on the screen. ...

Preventing Javascript Pop Up from automatically jumping to the top of the page

Upon clicking a button (refer to image below and take note of the scroll bar position), a div pop up is triggered through Javascript. View image: https://docs.google.com/file/d/0B1O3Ee_1Z5cRTko0anExazBBQkU/preview However, when the button is clicked, the ...

Placing a symbol like "@" at the beginning of a slug in a NextJS route

How can I include the "@" symbol in a slug URL? For instance: https://example.com/@username. I attempted using @[username].js, but it didn't work. Is there a different way to achieve this? Is it even feasible to have an "@" symbol in a slug URL? ...

Seeking insight on the implementation of the next() function in expressjs

I'm struggling to understand the concept of the next() method in express.js. I'm curious if next() is exclusive to express.js. Another question that comes to mind is, in the code snippet below, what exactly does next() do? Does it move to the fol ...

ReactJS rendering Express data as numbers instead of JSON format

My challenge involves sending strings from my Express server as a JSON object and then displaying these objects in my React app. Currently, instead of showing the expected data, it's simply displaying numbers for each of the 25 elements: 01234567891 ...

Crisscrossed JavaScript Object: recursion and "intricate" conversion (using lodash)

Apologies for the complexity of this example; I've condensed it as much as possible to demonstrate what I'm aiming for I have a complicated structure that needs to be traversed and transformed based on certain conditions. Here's a brief exa ...

Enhancing jQuery Component while making an Ajax request

When a user clicks a button, I am making an ajax call to send out multiple emails. My goal is to update a "Please wait..." div before and after the call with status updates, as well as report any errors that may occur. However, I have encountered an issue ...

Issue with Refresh Triggering Update, localStorage, useState, useEffect Combination

I want my app to execute the code inside the useEffect hook every 5 seconds, regardless of whether the page is refreshed or not. Currently, the code only runs when the page is refreshed and then remains inactive until the page is refreshed again. It seems ...

Alter the entity type when passing it as a parameter

Trying to alter the Entity type, I am invoking a function that requires two parameters - one being the entity and the other a location. However, when trying to assign a Type for the first entity, it throws an error: Error: Argument of type 'Node<En ...

Enhancing the Wireframe Design

Is there a way to display both the wireframe and the object itself, with vertices that update continuously using a shader? My code currently looks like this; var mainGeo = new THREE.SphereGeometry(100, 80, 80); var shaderMaterial = new THREE.ShaderMateri ...

Two states each offering a distinct perspective

I am currently working on modularizing my application using angular-ui-router to create a website with two states: main and checkout. In the main state, I want to have multiple "section" tags defined as ui-view items. However, it seems like there is an iss ...

What is the proper method for assigning a value to a variable within a JSON

While utilizing the js.cookie.js library available on Github, I encountered a challenge when attempting to set a JSON cookie. According to the documentation for js.cookie.js, in order to set a JSON cookie, the following syntax should be used: Cookies.set( ...

Tips for refining the data displayed on your Kendo Grid

I have implemented a Kendo grid in my view and I am looking to apply filters to the data displayed on the grid. The grid is populated from a list within my model. @(Html.Kendo().Grid(Model.list) .Name("listgrid") .Columns(columns => { ...

What are the advantages of using HttpClient compared to fetch?

With the introduction of Angular 2+, HttpClient now facilitates HTTP requests sent down an RxJS observable. I'm curious about why one would opt for using HttpClient's API instead of the standard fetch for individual HTTP requests. I have a good ...

Fetching Information From Database Using PHP

I am encountering an issue while attempting to transfer data from my HTML table to my modal (without using bootstrap). In the image below, you can see that I have successfully displayed data from MySQL database in the table. The problem arises when I clic ...

TimeStamp Recorder - Typescript

I'm trying to create a timer that counts the time when a button is pressed. Currently, I have managed to display the minutes and seconds on the screen as soon as the button is clicked. For example: 21(min):02(sec) What I am struggling with is updati ...

Why is it not possible to incorporate a variable in HTML when using Vue.js?

Why am I encountering an error when trying to use location information in HTML? The error message is Uncaught (in promise) TypeError: Cannot set properties of undefined (setting 'geoLocationPlace'). What could be causing the variable 'geoLoc ...