Can an onSnapshot event be set up for an array in order to track changes?

In my system, each user is associated with multiple groups. Each user's group membership is stored as an array within their user document. Additionally, there is a tasks collection where each task contains an array of authorizedGroups that correspond to the user's groups. While most tasks have just one authorizedGroup, some may have multiple. Tasks are assigned from one user to another.

I am looking to query for all tasks that are available to a specific user and set up listeners for each query. Although using get() has been successful in retrieving data, it does not provide the active listener functionality I require. Is there a method to generate listeners for each group? The onSnapshot method does not return a promise, making it unclear how I can achieve this desired outcome. Any suggestions or guidance on this matter would be greatly appreciated.

created() {
  const getTasksPerGroup = async (groups) => {
     // Make a get request using each group in the user's group membership list
     const queries = groups.map((group) => {
         return this.$store.state.db
             .collection('tasks')
             .where('authorizedGroups', 'array-contains', group)
             .where('taskAssignedTo', '==', this.$store.state.auth.user.displayName)
             .get()
      })

     // Use Await Promise.all to acquire an array of querySnapshots
     const result = await Promise.all(queries).then((querySnapshot) => {
         return querySnapshot.map((querySnapshot) => querySnapshot.docs).reduce((acc, docs) => [...acc, ...docs])
     })

     // Result is an array of querySnapshots...pushing each qs.data() to the tasks array
     let tasks = []
     result.forEach((qs) => {
         let item = qs.data()
         tasks.push(item)
         console.log('tasks:', tasks)
         this.$store.commit('tasks/mutate_tasksArray', tasks)
     })
 }

 // Invoke async function that gets the user's groups array
 getTasksPerGroup(this.allFirmGroups)
}

Answer №1

When working with Firestore, you have the option to either use get(), which returns a promise and provides a single set of results, or utilize onSnapshot() to attach a persistent listener. The latter does not return a promise because only you have control over when the listener stops.

If you need to listen to the results of multiple queries, you must add a listener to each one individually. When you are finished listening, make sure to unsubscribe from each listener without relying on any promises returned by the Firestore SDK. You are responsible for managing the timing of adding and removing these listeners.

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

Scale up the font size for all text on the website uniformly

Recently, I decided to switch a website's font to a non-web typeface. However, I quickly realized that the font was extremely thin and difficult to read. I attempted a simple CSS fix using * { font-size:125% }, but unfortunately, it did not have the d ...

Minimizing switch-case statement into inactive input field (AngularJS)

While the code statement functions as intended, it may not be considered best practice due to the repetition of variables in each case of the switch statement. I am unsure of how to streamline the code or if there is an alternative to using a switch statem ...

A JavaScript code snippet that stores the total number of bytes read from a CSV file in a variable

I currently have a CSV file located on a web server that is regularly updated with numeric and string data of varying lengths. I am seeking a solution to calculate the total byte values of each row when reading the file, as the byte count is crucial due ...

I'm looking to efficiently convert JSON or GeoJSON data into a Backbone model and then seamlessly transition that model into a Leaflet layer. Can anyone provide guidance on

As I work on refining layer definitions that can be added individually to a collection, my goal is to smoothly render the view or add them to a L.LayerGroup using the leaflet api. However, being new to JavaScript, I am uncertain about how to map the proper ...

Issue: The variable THREE has not been defined within the FBXLoader code

Currently, I am utilizing the module version of three.js in order to execute imports from a client-side JavaScript file structure. The core functionality of THREE is working correctly. However, I am encountering an issue when attempting to use it with FBX ...

Creating a Commentary System in VueJS Similar to Medium

One feature that I admire in Medium is their commenting interface, which allows users to highlight specific portions of an article and leave comments. I am interested in integrating a similar commenting feature into a VueJS application. While researching ...

Searching through different columns in various tables using the identical identifier, but with a reverse order

In the messages table for my chat application, I have columns labeled to and from, which store integers referencing users from the users table. My goal is to fetch all messages sent or received by the currently logged in user. Here is the query I am using ...

The value returned by $route.query.page is incorrect, or there may be an issue with type casting in the v-if condition

Currently, I am working on a posts page and the main focus is on pagination. I have developed a pagination component that has the following structure: <template> <nav aria-label="Pagination"> <ul class="pagination justify-cont ...

Create an array in JavaScript using the JSON data that was returned

After receiving some JSON data from a REST call, I have successfully parsed and added totals to the data. The results can be viewed on the page (refer to this post: json sibling data). However, now I want to further break down the totals. Here is the initi ...

React snap scrolling feature is not working as intended

I've been attempting to implement the snap scroll feature in my react app, but I'm facing issues with it. The regular CSS method doesn't seem to work well in Chrome, as discussed in this Scroll Snap Skips Section on Smaller Screen - Chrome t ...

Traversing an array of objects to extract and display the key-value pairs for each object

Here is an array I am working with: const cuisines = [ { african: "African" }, { american: "American" }, { arabian: "Arabian" }, { argentine: "Argentine" }, { asian: "Asian" }, { asian_fusion: "Asian Fusion" }, { australian: "Australi ...

The Vue.js route is not aligning with its defined path, causing a mismatch

Attempting to develop a Vue SPA app, but encountering an issue with the routes not matching what was defined in the router. Despite all configurations seemingly correct, there is confusion as to why this discrepancy exists. What element might be overlooked ...

Is it necessary to uncheck the row checkbox when inputs are left empty after blurred?

Two issues have cropped up here. When clicking on an input within a row, the corresponding checkbox should be checked. Currently, only the first text input is able to check the checkbox due to the use of .prev(). Is there a different approach that can be t ...

Spotfire: Changing a URL in an input field after it has been entered by the user

Currently, I am faced with a challenge related to importing a file in spotfire based on the path provided by the user. To accomplish this, I am utilizing a data function written in R script. In R, it is essential to note that all "\" characters are n ...

Looking to migrate my current firebase/react project to typescript. Any tips on how to batch.update?

Having difficulty resolving a typescript error related to batch.update in my code. const batch = db.batch(); const listingDoc = await db.collection("listings").doc(listingID).get(); const listingData = listingDoc.data( ...

The hyperlink and criteria provided are accurate, however, the webpage remains stagnant

My login page is supposed to redirect to the contact confirmation page when I receive a 200 response from the server, but it's not working. Can you help me find my mistake? const [form, setForm] = useState({}); async function checkLogin() { tr ...

Retrieving data from AJAX requests

I have an AJAX code that sends data to the server and returns results including id, name, and quantity. How can I extract and print only the quantity, id, or name? Thank you for your help! <script type="text/javascript"> $("#bto_update_quan ...

The incremental BR tag counter seems to be malfunctioning, there appears to be a missing element

Can anyone help me with the following code? I'm trying to add an incremental counter next to each BR tag in a lyric song, but it doesn't seem to be working as expected. <?php $lyrics = "<p>Every time when I look in the ...

Displaying Spinner and Component Simultaneously in React when State Changes with useEffect

Incorporating conditional rendering to display the spinner during the initial API call is crucial. Additionally, when the date changes in the dependency array of the useEffect, it triggers another API call. Question: If the data retrieval process is inco ...

Implementing a two-column infinite scrolling feature using ISCroll

I am looking to incorporate multi-column infinite scrolling using IScroll infinite scrolling. I want the content of my HTML to appear as follows: <ul> <li>A</li> <li>B</li> <li>C</li> <li>D</li> ...