Firestore generates an error stating that 'onSnapshot() must have 1 to 4 arguments'

I am having trouble retrieving all unread messages for the current user from Firebase. The issue arises when using onSnapshot() as it initially fetches the required data but fails to do so when a new document is added, resulting in an error.

FirebaseError: Function Query.onSnapshot() requires between 1 and 4 arguments, but was called with 0 arguments.

This function serves as a helper to get the count of all unread messages for the current user.

async getUnseenMessagesCount() {
    const collectionRef = (await firestore()).collection(this.collectionPath) //chats/${user_id+second_identifier/messages}
    let allMessagesCount = 0
    let currentUserReadMessagesCount = 0
    try {
      collectionRef.onSnapshot().then(snapshot => {
        allMessagesCount = snapshot.docs.length
      })
      collectionRef
        .where('seenBy', '==', '') // compare against empty string because seenBy is userId.
        .onSnapshot()
        .then(snapshot => {
          currentUserReadMessagesCount = snapshot.docs.length
        })
    } catch (error) {
      console.log(error)
    }

    console.log(allMessagesCount)
    console.log(currentUserReadMessagesCount)
    console.log(allMessagesCount - currentUserReadMessagesCount)
  }

To find the total count of unread messages across all chats the user is involved in, I perform the following operation within my Vuex action triggered by auth state changes:

new UserChatsDB(newUser.id).readAll().then(snapshot => { //users/id/chats/{chat_id: user_id+second_identifier}
        if (snapshot.length > 0) {
          snapshot.forEach(element => {
            console.log(element)
            const count = new MessagesDB(
              element.chat_id
            ).getUnseenMessagesCount()
            console.log(count) //Returns pending Promise
          })
        }
      })

What might be causing the aforementioned error? Is there a more effective approach to this problem? Please advise whether knowledge of the database structure would be helpful. Your assistance is greatly appreciated!

Answer â„–1

As stated in the documentation for Firebase, the recommended approach is to utilize the onSnapshot() function as shown below:

async getUnseenMessagesCount() {
    const collectionRef = (await firestore()).collection(this.collectionPath) //chats/${user_id+second_identifier/messages}
    let allMessagesCount = 0
    let currentUserReadMessagesCount = 0
    try {
      collectionRef.onSnapshot(snapshot => {
        allMessagesCount = snapshot.docs.length
      })
      collectionRef
        .where('seenBy', '==', '') // compare against empty string because seenBy is userId.
        .onSnapshot(snapshot => {
          currentUserReadMessagesCount = snapshot.docs.length
        })
    } catch (error) {
      console.log(error)
    }

    console.log(allMessagesCount)
    console.log(currentUserReadMessagesCount)
    console.log(allMessagesCount - currentUserReadMessagesCount)
  }

Hence, it's advised to eliminate the use of then() in this scenario.

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

Using PHP to send JSONP callback responses

Is it possible to achieve "two-way" communication using JSONP and PHP? For example: jQuery / JSONP $.ajax({ url: 'http://server/po.php', cache : false, dataType: 'jsonp', timeout: 30000, type: 'GET', ...

Conceal or remove disabled years in Angular Material datepicker

I previously disabled years prior to 2018, but now I would like to hide or delete them. The year selection range currently starts from 1998, but it should begin at 2018 instead. Is there a way to display only 3-4 years instead of the current 24-year rang ...

Is there a method to make this package compatible with Angular version 16?

I recently integrated the ngx-hotjar package version 11.0.0 into my Angular 10 project with success. However, when trying to use it in a new Angular 16 project, I encountered the following error during ng serve: Error: src/app/app.module.ts:275:12 - error ...

Click the "Add to Cart" button to make a purchase

Recently, I've been working on modeling an add to cart feature using jQuery. However, I have encountered a small issue that I'm trying to troubleshoot. When I click the mybtn button, the model displays and functions correctly, but there seems to ...

Mastering Inter-Composable Communication in Vue 3: A Guide

Composables in Vue documentation demonstrate how small composition functions can be used for organizing code by composing the app. Discover More About Extracting Composables for Code Organization "Extracted composables act as component-scoped servi ...

Flask - Refreshing Forms Dynamically

In an effort to enhance the responsiveness of my app, I am looking for a way to prevent the page from reloading every time a POST request is sent. My current setup includes a dynamically generated form with input fields designed like this: <div class=&q ...

Custom template for prefetched data is not displaying in Typeahead.js

I'm currently utilizing Twitter's typeahead.js plugin for displaying autocomplete suggestions. Here is the code snippet: $.ajax({ url:'/getlocals/', success: function(data){ $('.local-type').typeahead({ ...

Issue with passing parameters to function when calling NodeJS Mocha

I have the following function: export function ensurePathFormat(filePath: string, test = false) { console.log(test); if (!filePath || filePath === '') { if (test) { throw new Error('Invalid or empty path provided'); } ...

Tips for using Howler library in React to automatically play audio upon loading the page

I'm troubleshooting why the audio on my webpage won't start playing when the page loads, and instead only plays after a mouse click triggers an event. The audio works fine but I want it to automatically play as soon as the page is loaded. import ...

The pagination feature for Swiper is experiencing issues across both desktop and mobile platforms

I am having an issue with the pagination display in the text. I would like it to appear below the text as a standalone item for better visibility. Another problem arises when viewing the page on mobile devices - the hamburger menu displays behind the slid ...

What issues are hindering the successful export of my Vue component packaged with npm?

I created a small local npm package called fomantic-ui-vue with the following main js file: import Vue from 'vue' // Import vue component import button from './elements/button/button.vue' import buttonGroup from './elements/butt ...

Guide to defining the encoding of an XML file with JavaScript

Hi there, I am currently facing an issue with encoding while creating a document using JavaScript. The problem is that the document rejects all non-ascii characters. For example, when passing the string "verificación", it gets replaced by "". Any suggesti ...

Sort function now accepts a limitless amount of arguments for sorting

We are tasked with creating a function that can take an unlimited number of arguments to sort an array by. For example: var data = [['John','London',35], ['Ricky','Kuala Lumpur',38], [' ...

Issue with React and Mongoose: State Change Not Being Saved

I am facing an issue with changing the state of my checkbox. Initially, the default option in my Mongoose model is set to false. When a user checks the box and submits for the first time, it successfully updates their profile (changing the value to true). ...

What is the process for calculating and determining the exact area the div should be released?

I am currently developing a drag-and-drop application using only Javascript. I have successfully implemented the dragging functionality, allowing elements to be moved randomly within the page. However, I now face the challenge of creating a drop zone with ...

The contents of the image are currently unable to be viewed

I have a Blob of an image that I am trying to display in the browser. However, when I use the code below to open the image, it shows some Mandarin scripts on the window. Here is the code snippet: var url="http://....link..../downloadFile?fdsFileId="+file ...

When the button is clicked, the form will be submitted regardless of the button type

When submitting a form with ajax using vuejs, everything works fine except for the issue where pressing enter in the input field submits the form to itself. Despite using `form role=form` and `button type=button`, even when the button is outside the form, ...

The networking feature stops functioning on Android devices after upgrading from Ionic 1.5.0 to 1.6.3

After upgrading from ionic 1.5.0 to 1.6.3 (the latest version), I noticed that networking ajax calls were no longer working on Android. I had to remove and re-add the android platform, and there seemed to be a change in the apk names from MainActivity-debu ...

Obtaining the scene's coordinates in Three.js

Struggling with a coding issue, I've scanned various discussions that don't quite address my specific problem. Any assistance would be greatly appreciated. In my HTML document, I am using the three.js library to create a scene titled scaledScene ...

The error occurred in Commands.ts for Cypress, stating that the argument '"login"' cannot be assigned to the parameter of type 'keyof Chainable<any>))`

Attempting to simplify repetitive actions by utilizing commands.ts, such as requesting email and password. However, upon trying to implement this, I encounter an error for the login (Argument of type '"login"' is not assignable to parameter of t ...