Filtering a collection in Firestore using the `where()` method for a context provider in Next.js

i encountered an issue:

when using the useEffect function to retrieve my firestore documents, it works well. Currently, I am fetching all "profiles" documents (3 in total). However, I now want to only retrieve the documents where the field "workerProfile" is set to true. There are 2 documents with false and 1 document with true, so ideally, it should return an array with just 1 document.

Performing this manually in the firebase console yields the desired result.

https://i.sstatic.net/EvP6f.png

https://i.sstatic.net/3xncw.png

below you can see my useEffect function utilizing

,where('workerProfile', '==', true)
. Despite not throwing any errors, it does not filter out the unwanted documents either.

useEffect(() => {
        const getProfiles = async () => {
            const querySnapshot = await getDocs(collection(fireDb, "profiles"),where('workerProfile', '==', true))
            console.log(querySnapshot, "CHECK OUT")
            setProfiles(querySnapshot.docs.map(doc => {
                return {
                    id: doc.id,
                    data: {
                        userProfileUrl: doc.data().userProfileUrl,
                        displayName: doc.data().displayName,
                        likesCount: doc.data().likesCount,
                        bio: doc.data().bio
                    }
                }
            }))
        }
        getProfiles()
    }, [])

The

console.log(querySnapshot, "CHECK OUT")
still displays all 3 profiles instead of just 1.

https://i.sstatic.net/NB926.png

I have referred to the firebase documentation for guidance but remain puzzled by the issue. Perhaps I have overlooked something?

Any help would be greatly appreciated as this problem is becoming quite frustrating for me.

The technologies i'm working with include:

  • firebase 9.14.0
  • firebase-admin ^11.2.1
  • firebase-functions ^4.0.2
  • next 13.0.2
  • react: 18.2.0

Below you'll find my complete context-file for further reference:

import { createContext, useEffect, useState, useContext } from "react"
import { collection, getDocs, getDoc, doc, where, query, setDoc } from "firebase/firestore"
import { fireDb } from "../../firebaseClient"

const FantsyContext = createContext()

const FantsyProvider = ({ children }) => {

    const [users, setUsers] = useState([])
    const [currentLoggedUser, setCurrentUser] = useState([])
    const [profiles, setProfiles] = useState([])

    // GET USERS
    useEffect(() => {
        const getUsers = async () => {
            const querySnapshot = await getDocs(collection(fireDb, "users"))
            setUsers(querySnapshot.docs.map(doc => {
                return {
                    id: doc.id,
                    data: {
                        ...doc.data()
                    }
                }
            }))
        }
        getUsers()
    }, [])

    // GET PROFILES
    useEffect(() => {
        const getProfiles = async () => {
            const querySnapshot = await getDocs(collection(fireDb, "profiles"),where('workerProfile', '==', true))
            console.log(querySnapshot, "CHECK OUT")
            setProfiles(querySnapshot.docs.map(doc => {
                return {
                    id: doc.id,
                    data: {
                        userProfileUrl: doc.data().userProfileUrl,
                        displayName: doc.data().displayName,
                        likesCount: doc.data().likesCount,
                        bio: doc.data().bio
                    }
                }
            }))
        }
        getProfiles()
    }, [])

    return (
        <FantsyContext.Provider
            value={{ profiles, users }}
        >{children}</FantsyContext.Provider>
    )
}



export { FantsyContext, FantsyProvider }

Answer №1

Attempt

await fetchRecords(query(cache(fireDb, "profiles"), filter('workerProfile', '==', true)))

It seems that the implementation utilized

getDocs(collection(<ref>, <collection name>))
which caused the getDocs() function to overlook additional arguments within the where() query.

To resolve this issue, integrate the query() function within the getDocs() method.

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

Prevent the form from refreshing while still allowing for submission

I'm currently working on a radio website that features a player and several banners that can be clicked on to play different radios. In my opinion, the ideal behavior would be that when I click on a button to play a radio, it should smoothly transiti ...

Unable to transmit an object using ExpressJS

Greetings. I am currently trying to comprehend ExpressJS. My goal is to send a simple object from the express server, but it only displays "cannot get" on the screen. app.get("/", (req, res, next) => { console.log("middleware"); const error = true; ...

Struggling to connect API from React and Node using a proxy server

I have encountered a troubleshooting issue with React and Node that I am struggling to resolve. The problem lies in the communication between my node server and coinmarketcap API. While I successfully receive data from both endpoints (all coins and individ ...

AngularJS returns an empty array following a get request

Upon sending a GET request in my code example to retrieve a response array containing data, I noticed that the array appears empty in the console of Firefox. I am uncertain about where the error might be occurring. https://i.stack.imgur.com/aRWL9.jpg Belo ...

"Data passed to a JavaScript callback function may result in an undefined

I've been experiencing some issues with callbacks and getting return data as undefined. function goodMorning(name, msg) { return `${name} ${msg}`; } function greet(name, msg, cb) { const myName = "Sairam"; console.log(`${cb(name)} ${cb(msg)} ...

Generate a new entry by analyzing components from a separate array in a single line

I have a list of essential items and I aim to generate a record based on the elements within that list. Each item in the required list will correspond to an empty array in the exist record. Essentially, I am looking to condense the following code into one ...

Receiving a response from an XMLHttpRequest() within a function

I've come across a situation where I have a function called isOnline(), and here's how it looks: function isOnline() { var request=new XMLHttpRequest(); request.onreadystatechange=function() { if(request.readyState==4) { ...

What is the method to prevent the Submit Button from being active in CSS specifically on Firefox?

When I click this CSS in webpages on Chrome (OS: Windows), it works fine. However, Firefox (OS: CentOS7) does not seem to apply this CSS on webpages. How can I resolve this issue? Should I make adjustments in the CSS code below? #submit .btn.btn-primary ...

Tips for properly updating the shadow when modifying the vertices of custom geometry in A-Frame/three.js

I've developed a custom component in a-frame that generates a unique geometry. I'm using the tick function to animate the update of the geometry's vertices successfully. However, the shadow on the geometry doesn't seem to update accordi ...

Implementing conditional where clauses in Firestore queries with dynamic parameters

Consider this scenario: I have a dynamic filter list for my product list, and I want to send an HTTPS request to a cloud function based on the selected filters. However, when trying to set multiple conditional where clauses from that request... The multip ...

Having trouble locating the issue in my React application

As part of a tutorial project, I am developing an e-Commerce application using React. Currently, I am encountering an error message stating 'TypeError: Cannot read property 'length' of undefined' when dealing with a cart object. Let me ...

Passing a node.js variable to an ejs template through a post request

In my nodejs application, I utilize Express JS to handle post requests. Within the INDEX.JS FILE, the following code snippet is present: this.app.post('/profile', (req, res, next) => { let password = req.bo ...

Is it possible to utilize gulp to eliminate all require.js define([...]) wrappers throughout the codebase?

Is it possible to test my app without using require.js in order to assess the performance and file size if all files were concatenated into a single one? I'm contemplating using gulp to gather all *.js files in the app, running a gulp-replace to elim ...

tsconfig.json respects the baseUrl for absolute imports inconsistently

While using create-react-app, I have noticed that absolute imports work in some files but not in others. Directory Layout . +-- tsconfig.js +-- package.json +-- src | +-- components | | +-- ui | | | +-- Button | | | | +-- Button.tsx | ...

IE page refresh causing jQuery blur to malfunction

Our website features a textbox with a watermark that appears and disappears based on focus and blur events in jQuery. However, we have encountered a unique issue with Internet Explorer browsers. Whenever a user clicks on the textbox, the watermark disapp ...

Cypress has the ability to exclude certain elements from its testing

How do I locate a clickable element using the cypress tool? The clickable element always contains the text "Login" and is nested inside the container div. The challenge lies in not knowing whether it's an <button>, <a>, or <input type=& ...

I'm having trouble jotting down notes in the TextFields

I'm currently facing an issue when trying to add a new user to my database using the axios post method. I have created a form with Material UI, and although there are no console errors or browser issues, I am unable to input text into the TextFields. ...

Even though I have the image button's ID, I am unable to successfully click on it

I am facing an issue where I can't seem to click on an image button even though I know its ID: driver.findElement(By.id("its Id")).click() Unfortunately, I cannot provide the website link as it is not a public website. However, I have pasted the HTM ...

Positioning social media icons directly below the Avatar component

I've been working on aligning my social media icons under the Avatar component. Despite trying multiple methods to center them in the JSS, I haven't had much success. I attempted different approaches but couldn't achieve the desired alignmen ...

Detecting changes to DOM elements without using jQueryResponding to DOM element

Suppose I have the following HTML structure: <div id='content'></div> I want to receive an alert when there are height mutations on this element. I thought about using the MutationObserver class for this, but I encountered a specifi ...