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

Changing the font family for a single element in Next.js

One unique aspect of my project is its global font, however there is one element that randomly pulls font families from a hosted URL. For example: https://*****.com/file/fonts/Parnian.ttf My page operates as a client-side rendered application (CSR). So, ...

Submitting a form automatically in React Native using Redux

Is there a way to automatically submit a Redux Form in React Native based on certain conditions being met? I attempted to do so below, but it resulted in a warning. The documentation provides an example for remote submitting, but it uses HTML form's ...

Updating interval time based on an external variable with jQuery

I have developed a JavaScript script where pressing a button triggers the continuous playback of an audio file. The audio, which is a 'beep' sound, serves as an alarm. The frequency at which the beep plays is determined by a setting located on a ...

Bring a div box to life using AngularJS

Struggling to animate a div-Box in AngularJS? Despite trying multiple examples, the animation just won't cooperate. I'm aiming to implement a feature where clicking on a button triggers a transition animation to display the search form. I under ...

Using regular expressions to validate input in Javascript

Seeking assistance to validate an input text using the pattern <some_string>:<some_string> in JS/JQuery. For instance: A110:B120 AB12C:B123 I understand this might seem overly simplistic, but any guidance would be greatly appreciated. ...

There was a rendering error: "Type Error: Unable to access the 'PAY_TYPE' property of null"

I am attempting to retrieve the PAY_TYPE value from the callback_details object by using JSON.parse() function to convert a string into an object. However, I keep encountering an error related to the question's title. Here is my code snippet: <td ...

Incorporating a complex React (Typescript) component into an HTML page: A Step-by

I used to have an old website that was originally built with Vanilia Javascript. Now, I am in the process of converting it to React and encountering some issues. I am trying to render a compound React(Typescript) component on an HTML page, but unfortunatel ...

The date-fns parse function will retrieve the value from the previous day

When attempting to parse a date using the date-fns library, I am encountering an issue where the resulting date is one day prior. How can this be resolved in order to obtain the correct result? start = '2021-08-16' const parseStart = parse(start, ...

What could be causing the issue with updating a js file using ajax?

I've been dealing with a php file called users. Initially, everything was going smoothly as I wrote some JavaScript code for it. However, after making updates to the JavaScript code, it seems to have stopped functioning. Below is the content of the p ...

Using a PHP array as a parameter in a link for an AJAX function

I am attempting to pass a PHP array to an AJAX function in order to populate dynamically created tables. To achieve this, I need to pass the values in an array all at once to avoid the issue where only the last dynamic table is populated. However, it see ...

Retrieving an array of various responses using Axios

My current code includes a function that retrieves exchange rates for various stocks: export const getRates = (symbole1, symbole2, symbole3) => { const res = [] axios.all([ axios.get(`${baseUrl}/${symbole1}`), axios.get(`${ ...

Submitting a JSPX form to interact with PHP backend

Can a JSP/JSPX form be used to submit data to a PHP file? The PHP file will handle validation and database updates, then send a response back to the same JSP/JSPX form. The process should be done using AJAX with jQuery. What steps are involved in achievi ...

Is there a way to immobilize an object in JavaScript without resorting to Object.freeze()?

Is there a way to freeze the following object without relying on Object.freeze()? Let's find out: const obj = { a:'test', b:'Something' } ...

Choosing multiple images using JavaScript/jQuery

Gridster is being used for a webpage, with widgets containing images that can be added and deleted using the "+" and "X" buttons. Current Status Clicking the "+" button opens a modal where multiple images can be selected and added to the widgets by click ...

Tips for preserving component state during page rerenders or changes

I created a counter with context API in React, and I'm looking for a way to persist the state even when the page is changed. Is there a method to store the Counter value during page transitions, similar to session storage? My app utilizes React Router ...

React Native vector icons display enigmatic symbols

I recently installed react-native-vector, but I'm seeing strange symbols when using it. Can anyone provide guidance on how to properly utilize this library? Platform: Android import React from 'react'; import {View, Text, StyleSheet} from & ...

In case of an API error with the Nuxt fetch method, ensure that the entire site responds with a 404

Is it possible to configure a Nuxt website to respond with a 404 error when the API raises a 404 error? The API call is made on the client side using the fetch method: Check out this demo here: codesandbox demo Code Snippets index.vue <template> ...

Creating an HTML list based on a hierarchical MySQL table structure

I have retrieved a hierarchical table showing different elements and their parent-child relationships as follows: id| name | parent_id | header 1 | Assets | 0 | Y 2 | Fixed Assets | 1 | Y 3 | Asset One | 2 | N 4 | ...

What steps should I take to incorporate the delete feature as described above?

Click here to access the delete functionality Hello there, I need help implementing a delete function similar to the one provided in the link above. Below is the code snippet for your reference. I am utilizing the map method to extract data from an array ...

Transferring an array to PHP using AJAX

In this coding scenario, I initialize my array: let myArray = []; Within a loop, elements are added to the array as follows: myArray.push($(this).data('id')); // Example: [1, 2, 3, 4] Subsequently, I transmit this data to PHP using AJAX throu ...