Is it possible to create a persistent real-time listener for Firestore on either the client or server side?

I am a newcomer to utilizing firebase and my objective is to read all data in a collection just once, then continuously fetch new updates without the need to refetch all the data when refreshing or closing the web app.

Is this achievable?

<pre>db.collection("cities").where("state", "==", "CA")
.onSnapshot(function(snapshot) {
    snapshot.docChanges().forEach(function(change) {
        if (change.type === "added") {
            console.log("New city: ", change.doc.data());
        }
        if (change.type === "modified") {
            console.log("Modified city: ", change.doc.data());
        }
        if (change.type === "removed") {
            console.log("Removed city: ", change.doc.data());
        }
    });
});
</pre>

Answer №1

Once the application or process running the query is shut down, it's impossible to keep a listener functioning.

One alternative approach is to incorporate a timestamp field in every document and employ it to search for new documents created after the last one with a known timestamp that was read previously.

Answer №2

Listening for changes in real-time can be done using snapshot.docChanges(). Have you tried this method?

If you're looking for an example, I once used a similar approach in a live chat application. Placing the code snippet inside the created hook made it possible to fetch data from Firestore documents and automatically display new messages without refreshing the page.

For instance:

created() {

    let ref = firestore.collection('< your collection >')
              .doc('< document ID >')
              .collection('< sub-collection if applicable >')
              .orderBy('createdAt')

    ref.onSnapshot(snapshot => {

      snapshot.docChanges().forEach(change => {

        if(change.type == 'added') {
          let doc = change.doc

          this.messages.push({
            id: doc.id,
            name: doc.data().name,
            content: doc.data().content,
            timestamp: moment(doc.data().createdAt).format('lll'),
          })
        }
      });

    })
  },

In the data section, declare an empty array named 'messages' to store document contents and update them dynamically on any changes.

messages: [],

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

What is the method for changing the Uint8Array object into a string?

I am encountering a similar issue as the one discussed in this post. I have read the solution provided, but I am having trouble grasping how to implement it. Are there any alternative suggestions? Here is my code snippet: var eccrypto = require("eccrypto ...

Having trouble making an AJAX request work in AngularJS?

Just dipped my toes into the world of Angular (only a few hours in). Managed to tweak the demo to get close to what I need, but hitting a roadblock with my AJAX request. After trying a variety of fixes, one puts me in an endless loop (discovered that&apos ...

Encountering Rollup 2 Error: `'default' is not being exported`

Recently, I made the transition from Rollup version 1.27 to 2.48. In my rollup.config.js file, I included this dependency: alias({ Paths: { 'uikit-util': './node_modules/uikit/src/js/util', }, Extensions: ['js& ...

Connect to Node-Red websocket server

My server is running node-red with embedded functionality. I am attempting to set up a new websocket listener on the server, but when I run the code provided, the websockets in my node-red application stop functioning properly. const WebSocket = require(& ...

Three.js experiencing issues with FBX animations running erratically

Having trouble with animations on some fbx models. When an animation lasts 20 seconds, the model remains stationary for 19 seconds and then suddenly moves within the last second or so. However, other fbx models animate correctly. The code used to run the a ...

What issue is there with the href attribute in the pug file?

/users/mihir/users/[object%20Object]/file.txt My pug file and JS code are set up to render a pug page with links for directories and files in the specified path. The problem arises when adding "users/" plus a username before the directory or filename whil ...

Protractor and Jasmine fail to fulfill the promise of retrieving a webpage title

I am facing an issue with my protractor/jasmine test code where it only prints out 1 and 2, then hangs and times out. It seems like there might be a problem with the click() action on the button element or the promise on the getTitle method of the browser ...

The website functions well in responsive design mode on an iPad screen, but encounters issues when viewed on an actual

The website is functioning well in responsive design mode on an iPad screen, however it seems to be having some issues specifically on iPad devices. I have tested it on all other devices and it works perfectly fine, but for some reason not on iPads. Feel ...

Encountering an issue while fetching information from a JSON file using JavaScript

I am encountering an Uncaught SyntaxError: JSON.parse: unexpected character at line 1 column 1 of the JSON data let mydata = JSON.parse("file.json"); console.log(myJSON) Here is a sample of the JSON file's data: [[1,1,0,1,1,0,0,0,1,1,1,1,1, ...

Determine the time difference between two dates, taking into account Daylight Saving Time adjustments

If a start date and number of days are given, I need to calculate the end date by adding the number of days to the start date. This is the code snippet I used: var endDate=new Date(startDate.getTime()+ONE_DAY); Everything was working fine until I notice ...

karma is failing to run the test scenario

I am just starting out with karma and I'm having trouble running test cases. Below is my setup: karma.config.js module.exports = function(config) { config.set({ // base path that will be used to resolve all patterns (eg. files, exclude) base ...

Switching the cursor to an image when hovering over an element is causing inconsistency in hover events triggering

Currently, I am attempting to implement an effect that changes the cursor to an image when hovering over a text element and reverts back to the normal cursor upon leaving the text element. However, this functionality is not working as expected when using R ...

Transmitting special symbols through Socket.io

I've been working on a small project based on Socketio 0.9 and everything is running smoothly, except for a minor problem with special characters. In the web client, I am creating a dynamic JSON object using JavaScript that is then emitted to the ser ...

The ground shadows appear distorted and muddled

In my Threejs project, I have implemented a method to dynamically create a ground using perlin noise. The code snippet is shown below: createGround() { const resolutionX = 100 const resolutionY = 100 const actualResolutionX = resolutionX + 1 const actua ...

Can anyone provide guidance on uploading data to a mongodb database? I've attempted a few methods but keep encountering errors

const info = { name, price, quantity, image, desc, sup_name, email } fetch('https://gentle-plateau-90897.herokuapp.com/fruits', { method: 'POST', headers: { 'content-type': 'application/jso ...

After rendering express, Node.js establishes a connection to a TCP socket

I am currently working on a project involving a node.js web server, a TCP client, and a Java TCP server, all for the purpose of studying socket and web programming. The idea is that a user connects to a webpage, inputs some information, Node.js sends this ...

No results found by Mongoose find() method

I've set up a route that utilizes a model named Todo as shown below: app.get('/api/todos', function(req, res) { Todo.find({},function(err, todos) { if (err) res.send(err); console.log("number of todos " + tod ...

Utilizing Vue exclusively as a view engine in Sails.js, bypassing the need for a traditional

Currently, I am in the process of setting up an email server using Sails.js without any frontend capabilities. I am facing difficulty in importing a vue file into my controller or configuring the getRenderFn in the View.js file to render the vue file. I h ...

What is the best approach to generate and organize 100 random numbers in a program, ensuring they are sorted in ascending order from 1 to 100?

I have successfully implemented the sorting and printout functionality of the program. However, I am now facing a challenge in generating 100 random numbers between 1 and 100, sorting them. I have created an array to store the generated numbers, and I ha ...

Overcoming validation hurdles with PHP and JavaScript

Our form pages have a majority of required fields, which are verified using JavaScript before being sent to a backend PHP app. Here is the form tag we utilize: <form name="order" method="post" action="http://company.com/config/_process.php?" id="order ...