retrieving particular information from within a Firebase array

My Firebase document contains a list with various properties such as name and imgUrl. Currently, I am facing an issue with extracting only the "name:" information from the list in Firebase Cloud Firestore so that I can determine how many times a specific name appears.

Here is how I retrieve the data from the document:

 const matchLikes = async () => {
       await fire.firestore()
        .collection("eventLikes")
        .doc(eventID).onSnapshot((querySnapshot) => {
            
                //console.log("print indi event heree  " + querySnapshot.data().eventID)
              
                setLikes(querySnapshot.data().ActivityLikes)
              
            
        })

I have stored the array in a hook for use, but I am struggling to access just the "name:" information within the array. I have attempted using

querySnapshot.data().ActivityLikes.name
, but it does not work as expected. Can anyone help me identify where I might be making a mistake?

Answer №1

Unfortunately, Firestore does not have built-in support for projecting specific fields and aggregating data. This means you'll need to fetch the document and manually calculate the count of each name. Additionally, there is no need for an await before onSnapshot. Consider refactoring your code like so:

const calculateLikes = () => {
  fire.firestore()
    .collection("eventLikes")
    .doc(eventID)
    .onSnapshot((docSnapshot) => {
      const nameCounts = docSnapshot.data().ActivityLikes.reduce((acc, cur) => {
        acc[cur.name] = (acc[cur.name] || 0) + 1;
        return acc;
      }, {});
    
      // setLikes(querySnapshot.data().ActivityLikes)
    })
}

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

Error message: Unable to assign value to 'kind' property as it is undefined in Angular Webpack application

Unexpectedly, my Angular application is encountering an error during the build process. TypeError: C:\Users\c\dev\privacy\node_modules\@fortawesome\angular-fontawesome\fesm2020\angular-fontawesome.mjs: Cannot se ...

Having trouble converting binary data to base64 using GridFS-stream

As I attempt to convert some binary data from uploaded images to base64 in order to display an image, the terminal is throwing back this error: TypeError: Cannot read property 'on' of undefined I find it puzzling, as when I post I also utilize ...

Upon selecting a checkbox, I desire for a corresponding checkbox to also be marked

I am looking to enhance my current project by incorporating a feature that allows the user to simply check a checkbox with specific content once. For example, I have a recipes page where users can select ingredients they need for each recipe while planning ...

The coexistence of conflicting extensions, such as Metamask and Trust Wallet, both attempting to interact

I am working on developing a personal service that I want to integrate with browser extensions like Metamask and Trust Wallet, with the potential to include others in the future. However, I am facing challenges in finding resources on how to access the nec ...

Angular - Manipulating the selected option in a select box from the controller

My issue involves a select box that is defined in the following manner: <select ng-model="selectedSupplier" ng-options="supplier.name for supplier in suppliers"> </select> Within my controller, there is a button that doesn't have any r ...

Editable content <div>: Cursor position begins prior to the placeholder

Having an issue with a contenteditable div where the placeholder text starts behind the cursor instead of at the cursor position. Any suggestions on how to correct this? <div id="input_box" contenteditable="true" autofocus="autofocus" autocomplete="o ...

Difficulty encountered while attempting to deploy the front-end on Heroku

I recently completed a typeorm project with the following structure: https://i.stack.imgur.com/ReQK1.png Both the client and root directories contain index files located in the src directory. In the package.json file within the client directory, I made a ...

How to align an image in the center of a circular flex container

I'm facing an issue in my Angular project where I have the following code snippet: onChange(event: any) { var reader = new FileReader(); reader.onload = (event: any) => { this.url = event.target.result; }; reader.readAsData ...

CSS style takes precedence over inline JavaScript transitions occurring from a negative position

I am puzzled by a JavaScript fiddle I created which contains two small boxes inside a larger box. Upon clicking either of the buttons labeled "Run B" or "Run C", the corresponding box undergoes a CSS transition that is controlled by JavaScript. Below is t ...

Generating binary payload with Node-RED

Recently started with node-red and javascript. I am looking to establish a connection with a relay controller for status using the TCP input. I have configured a function node to create a two-byte request which will be sent through the TCP input node to th ...

Typescript inheritance results in an undefined value being returned

I am trying to understand the code below, as I am confused about its functionality. In languages like C# or Java, using the base or super keyword usually returns values, whereas in TypeScript, I am receiving "undefined". However, when I switch from using " ...

The error message "Unable to iterate over undefined property in Node.js using EJS and JavaScript" popped up

I've been struggling with the error "Cannot read property 'forEach of undefined" for two days now and I just can't seem to figure out the problem. Any help would be greatly appreciated. Here is the code: bruidstaart.js page where I am tryin ...

Is there a way to retrieve and gather all data from various scopes and then access them collectively?

I attempted to scrape information from a website using Node.JS + Cheerio + Axios. I was able to retrieve all the necessary data, but encountered an issue with returning the data from different scopes in order to receive it. Currently, I can only obtain the ...

Issue with Firebase authentication failing upon page reload

I'm currently delving into a project that involves the integration of Firebase and React. I have successfully implemented registration and login functionalities, but now I am seeking to add some form of security in order to control access to certain p ...

'An error occurred when invoking the class method due to 'This' being undefined

I'm attempting to display a response message to the user, but encountering an error (Cannot read property 'message' of undefined). Here's the code snippet causing the issue: server.js const server = express(); let App = require(' ...

Angular2: Leveraging click events to manage CSS classes on elements

I am currently developing a web app using Angular 2. I'm facing an issue where the active element should receive an extra CSS class when clicked, but adding the ":active" CSS attribute with a custom class doesn't work as expected. The ":focus" pr ...

Why is it that Next Auth states that the client_id is a required field when using their authentication system, even though in the Discord providers section there is

Each time I attempt to utilize next auth for creating a discord oauth client and subsequently click sign in, an error occurs: https://next-auth.js.org/errors#get_authorization_url_error client_id is required { message: 'client_id is required', ...

Ensure that the Popover vanishes upon scrolling the page - Material UI (MUI) v5 compatibility with React

When implementing the MUI v5 standard pattern for displaying a popover upon hovering over another element, everything works smoothly except for one scenario: If you hover over the element And without moving the mouse, use the scroll wheel to scroll throug ...

The conditional statements within the resize function may not always be triggered when the conditions are fulfilled

Struggling to trigger a function only once when resizing. The issue is that the conditional statements are not consistently executed every time. Here's the code snippet: var old_width = $(window).width(); $(window).on('resize.3col',functio ...

How to fetch images from a database in CodeIgniter by utilizing JSON and AJAX functions?

Trying to retrieve an image using ajax/json format for the first time, all variables are displaying except the image. The name of the image is visible when inspecting the element in the browser and it is saving correctly into the image folder. I need help ...