What is the best way to monitor updates made to a function that utilizes firestore's onSnapShot method?

I am currently working with the following function:

public GetExercisePosts(user: User): ExercisePost[] {
    const exercisePosts = new Array<ExercisePost>();
    firebase.firestore().collection('exercise-posts').where('created-by', '==', user.Id).onSnapshot((results) => {
      results.forEach((postDoc) => {
        const exercisePost = Deserializer.DeserializeExercisePost(postDoc);
        if (exercisePost) {
          exercisePosts.push(exercisePost);
        }
      });
    });
    return exercisePosts;
  }

Another react component will make use of this function like so:

public async componentDidMount() {
    const personalExercisePosts = this.exerciseService.GetExercisePosts(this.state.currentUser);
    this.setState({ personalExercisePosts });
  }

The functionality works perfectly for the initial call. However, I have noticed that the original GetExercisePosts method is not triggered again when the snapshot changes. This behavior is expected as componentDidMount only gets executed once in a component's lifecycle. Despite this, the snapshot function does get called whenever there are changes, which is evident when a new record is added through the Firestore admin console.

Is there a way to observe and respond to changes made to the snapshot? Maybe by setting up the snapshot to emit a change event that the component can listen for. While I am aware that introducing Redux could solve this issue, I would prefer to explore alternative solutions at this point.

Answer №1

To ensure that the snapshot is constantly monitored for changes, consider setting up a callback function instead of simply returning a response. Here's an example of how you can implement this:

function fetchUserExercisePosts(user, callback) {
    const exercisePosts = [];
    firebase.firestore().collection('exercise-posts').where('created-by', '==', user.Id).onSnapshot((results) => {
        results.forEach((postDoc) => {
            const exercisePost = Deserializer.DeserializeExercisePost(postDoc);
            if (exercisePost) {
                exercisePosts.push(exercisePost);
            }
        });
        callback(exercisePosts);
    });
}

async componentDidMount() {
    const personalExercisePosts = this.exerciseService.GetExercisePosts(this.state.currentUser, (posts) => {
        this.setState({ posts });
    });
}

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

Exploring Cypress: Iterating over a collection of elements

I have a small code snippet that retrieves an array of checkboxes or checkbox labels using cy.get in my Angular application. When looping through the array to click on each element and check the checkboxes, it works fine if the array contains only one elem ...

Swap out the selector of an Ionic2 component with its contents

I am utilizing Ionic2 along with TypeScript. Let's assume I desire a custom component to include the content of an ion-menu. <sidemenu></sidemenu> //This sidemenu will contain the ion.menu. <ion-nav id="nav" [root]="rootPage" ...

Tips for integrating Typescript Definition files with Visual Studio 2017

I have a challenge with my ASP.NET Core 2.0 application where I am attempting to incorporate TypeScript and jQuery. While TypeScript integration has been successful, I am facing issues with jQuery as it does not provide me with intellisense. Despite trying ...

Having Trouble with Angular 6 Subject Subscription

I have created an HTTP interceptor in Angular that emits a 'string' when a request starts and ends: @Injectable({ providedIn: 'root' }) export class LoadingIndicatorService implements HttpInterceptor { private loadingIndicatorSour ...

Is there a way to assign API data as inner HTML using Lit?

Need help setting inner html of html elements with a get request Any suggestions on how to achieve this? import { LitElement, html, css } from "lit"; import { customElement } from "lit/decorators.js"; import axios from "axios" ...

Identifying numerous RCTRootViews originating from a single RCTBridge

I have a situation where multiple RCTRootViews are present in various UIViewControllers, all of which share the same RCTBridge. Upon examining the source code, I discovered that RCTUIManager stores all the RCTRootViews with the Key "ReactTag". One specif ...

Using TypeScript to wrap a class with a Proxy object

I've been working on a function that takes an API interface (I've provided a sample here) and creates a Proxy around it. This allows me to intercept calls to the API's methods, enabling logging, custom error handling, etc. I'm running i ...

The bundling process encountered an error due to the absence of a file or directory while scanning in React Native

I'm facing an issue with my project where there are no errors present, but the build is not loading successfully. You can see the image below for more details on this error. I've been using the command react-native run-android to run the build, b ...

Using WebSockets in Angular 4

Currently in the process of developing a chat application using Angular 4 and WebSocket. I found guidance from this Angular WebSocket tutorial This is the source code for the WebsocketService: import { Injectable } from '@angular/core'; import ...

Error in typescript: The property 'exact' is not found in the type 'IntrinsicAttributes & RouteProps'

While trying to set up private routing in Typescript, I encountered the following error. Can anyone provide assistance? Type '{ exact: true; render: (routerProps: RouterProps) => Element; }' is not compatible with type 'IntrinsicAttribu ...

What is the best way to retrieve and showcase data in NextJs version 13 and beyond?

Being new to NextJS, my question may seem trivial but I'd appreciate your patience. Essentially, my goal is to fetch data from a database and display it on the page upon the initial render. To achieve this, I am utilizing the useEffect and useState ho ...

Is there a way to carry out tests on keydown events within Jasmine by specifying the keyCode within an Angular2+

I am working on a project where I need to trigger keydown events on an <input> field. Tools Used Karma v1.7.1 as the test runner Tests running on Chrome browser Using Angular 5 framework Any insights on how I can achieve this? ...

Error: The variable _ is undefined when trying to use the .map() function on an array

While working on my project, I encountered a "ReferenceError: _ is not defined" when using the .map function in this code snippet: arr.map(async (elem) => { ... }); I couldn't find any explicit mention of "_" in my code. The error trace pointed me ...

What steps should I take to choose esNext from the typescript menu within visual studio 2017?

When utilizing dynamic import with TypeScript in Visual Studio 2017, I encountered the following error: TS1323(TS) Dynamic imports are only supported when the '--module' flag is set to 'commonjs' or 'esNext'. I attempted to c ...

rxjs - monitoring several observables and triggering a response upon any alteration

Is there a way to watch multiple observables and execute a function whenever any of them change? I am looking for a solution similar to the functionality of zip, but without requiring every observable to update its value. Also, forkJoin isn't suitable ...

Potential absence of value in this Vue 3 component's 'this' placement

I've been encountering an issue with using this.$refs within my Vue component. No matter where I place it - whether in methods, lambdas, or lifecycle hooks - I consistently receive errors indicating that 'this' may be undefined. As a newcome ...

Locate and retrieve the item that appears most often in a given array

In order to determine the mode of an array consisting of integer numbers only, I must create a function named findMode. If the array is empty, the function should return 0. Otherwise, it should return the element that occurs most frequently in the array. I ...

Having trouble deploying Firebase Cloud function following the migration to Typescript

After following the steps outlined in the firebase documentation to convert my cloud functions project to TypeScript (see https://firebase.google.com/docs/functions/typescript), I encountered an error when attempting to deploy using 'firebase deploy - ...

What is the best way to exempt a unique situation from a directive's operation?

While troubleshooting a bug related to search functionality on my page, I encountered an issue with the search component. The search feature is working correctly and returning the expected values. However, when I clear the search criteria, I noticed that t ...

Can you explain the process for accessing a parent function in Angular?

I have a form component that inserts data into a database upon submission, and I need to update the displayed data in another component once it changes in the database. I attempted using ViewChild to invoke the necessary functions, but encountered issues w ...