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 ways to interact with an API using arrays through interfaces in Angular CLI

I am currently utilizing Angular 7 and I have a REST API that provides the following data: {"Plate":"MIN123","Certifications":[{"File":"KIO","Date":"12-02-2018","Number":1},{"File":"KIO","Date":"12-02-2018","Number":1},{"File":"preventive","StartDate":"06 ...

Creating a structure within a stencil web component

In my current project, I am utilizing Stencil.js (typescript) and need to integrate this selectbox. Below is the code snippet: import { Component, h, JSX, Prop, Element } from '@stencil/core'; import Selectr from 'mobius1-selectr'; @ ...

Tips for detecting the end of a scroll view in a list view

I've encountered an issue with my scrollView that allows for infinite scrolling until the banner or container disappears. What I'm aiming for is to restrict scrolling once you reach the last section, like number 3, to prevent the name part from m ...

Performing an Axios POST request in a React Native and React app using JSON.stringify and Blob functionality

I am currently developing an application where I have encountered an issue when calling an API endpoint in react native. Interestingly, the web app (built with React) does not encounter any errors. Here is the code for the web app using React with TypeScri ...

What are the properties used in functional components of React?

Seeking guidance on passing React component props to another component: interface IMyComponent { props: Props<any> } const MyComponent: FC = ({ props }) => { } Previously, I attempted to utilize the React.Props type after consulting this que ...

Is there a way to fetch a particular object from Firebase database based on its value using AngularFire2?

Here is the database I am working with: firebase database I am trying to retrieve a dish that has its 'featured' attribute set to true (dish.feature = true). Is it possible to do this directly from the database, or do I have to retrieve all di ...

The routes.js file is experiencing issues when a seemingly redundant mapStateToProps is removed, causing it

Currently in the process of cleaning up my code and stumbled upon something peculiar - I noticed a mapStateToProps and connect that are not being utilized anywhere within the file: import React from 'react'; import { Scene, Router, ActionConst, ...

What is the best way to import a TypeScript file in index.js?

I've recently developed an application using the react-express-starter template. I have a "server" directory where the backend is created by nodejs, containing an index.js file: const express = require('express'); const app = express(); c ...

Angular 5 error handler does not support service calls

My HTTP calls are placed inside a service, as they should be. Within that service, I inject another service for handling error notifications. In an interesting turn of events, I noticed that when I place the notification call inside the catchError pipe, e ...

Passing variables to nested components in React Native allows for easier data sharing

Currently, I am facing an issue with my camera and zoom components. They are separate because changing the state in the camera causes it to continuously reload. My problem lies in the fact that I am unable to find a way to pass the zoom variable to the cam ...

Referring to a component type causes a cycle of dependencies

I have a unique situation where I am using a single service to open multiple dialogs, some of which can trigger other dialogs through the same service. The dynamic dialog service from PrimeNg is being used to open a dialog component by Type<any>. Ho ...

Tips for showcasing individual row information in a popup window with Angular 9

Here is the code snippet for utilizing the open dialog method in the component: import { Component, OnInit } from '@angular/core'; import { HttpClient } from '@angular/common/http'; import { AuthService } from '../_services/auth.se ...

Node.js is known for automatically adding double quotes to strings. However, is there a way to eliminate them?

After creating a unit test, I noticed that both logics I used led to the same issue. Logic 1: describe('aresFileCopier', () => { test('log error', async () => { await registerDB('ares-test', { client: ' ...

When using Protractor with Typescript, you may encounter the error message "Failed: Cannot read property 'sendKeys' of undefined"

Having trouble creating Protractor JS spec files using TypeScript? Running into an error with the converted spec files? Error Message: Failed - calculator_1.calculator.prototype.getResult is not a function Check out the TypeScript files below: calculato ...

Why is the dateclick event in PrimeNG's FullCalendar not being emitted when clicking on a date? What is the best way to handle click events on specific dates within the calendar?

I am new to using Angular and PrimeNG, and I am facing challenges while trying to implement the FullCalendar component. The specific component I am referring to can be found here: The issue arises when I attempt to trigger an event when a user clicks on a ...

Why is my React Native button's onPress event not functioning correctly?

I am encountering an issue with the onPress event handler. I have tried multiple solutions but none seem to work with the handleClick function. Here are the different approaches I attempted: onPress={this.handleClick} onPress={this.handleClick()} onPress= ...

Different tsconfigs assigned to various directories

In my project, I am using Next.js with TypeScript and Cypress for E2E tests. The challenge I am facing is configuring tsc to handle multiple configs for different folders. The tsconfig.json file in the project root for Next.js looks like this: { "c ...

Troubleshooting Puppeteer compatibility issues when using TypeScript and esModuleInterop

When attempting to use puppeteer with TypeScript and setting esModuleInterop=true in tsconfig.json, an error occurs stating puppeteer.launch is not a function If I try to import puppeteer using import * as puppeteer from "puppeteer" My questi ...

Filter error - Unable to retrieve property 'toLowerCase' from null value

When filtering the input against the cached query result, I convert both the user input value and database values to lowercase for comparison. result = this.cachedResults.filter(f => f.prj.toLowerCase().indexOf((this.sV).toLowerCase()) !== -1); This ...

What is the best way to configure webpack for ng build instead of ng serve?

My .NET web application is hosted in IIS and it also hosts an Angular application. This setup requires both applications to be served on the same port by IIS, primarily because they share the same session cookie. Additionally, they are integral parts of th ...