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.

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.

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

Tips for updating a reactive form with multiple layers of nested JSON values

I am tasked with retrieving and working with the data from a deeply nested (potentially infinite levels) reactive form that includes formArrays, formGroups, and formControls. This data is stored in a database. Currently, my approach involves patching the ...

In-line Vertical Ticker Display

I attempted to use vTicker, but I found that it does not function properly when used as an inline element. <h1> <div id="vticker"><ul>...</ul></div> Some other headline text </h1> My goal is to have the vertica ...

Issue in Angular: Attempting to access properties of undefined (specifically 'CustomHeaderComponent')

I have encountered a persistent error message while working on a new component for my project. Despite double-checking the injection code and ensuring that the module and component export logic are correct, I am unable to pinpoint the issue. custom-header ...

Unpredictable jQuery Ajax setTimeout

I have a script that retrieves data from ajax.php and displays it in a div. The intention is for the information to be shown for a period of 3 seconds before hiding the #ajax-content and displaying #welcome-content. Most of the time it works as intended, ...

Problem with Selenium WebDriver: Some HTML elements are not being displayed

I am currently working on a python web scraper. Here is the code I have written: from selenium.webdriver.chrome.options import Options from selenium import webdriver from bs4 import BeautifulSoup chrome_options = Options() chrome_options.add_argument(&qu ...

What is the process for extracting an object from an array?

As a newcomer to jQuery, I've encountered an issue that has me stuck. My problem lies in accessing an array within an object. Here's the structure of my object as shown during debugging: cache:object 0001-:Array[2] 0:value1, ...

Create a pop-up box that appears beneath the anchor elements within Tiptap

I am currently in the process of developing an editor using Tiptap and I am facing challenges with implementing a notion-style anchor element in my rich text editor. Essentially, I need to display a tooltip below the links containing the href and an optio ...

Tips on avoiding the accumulation of event handlers when dealing with click events triggered by the document selector in jQuery

I am currently working on a project that involves using AJAX to load various pieces of HTML code. This is done in order to properly position dynamic buttons within each portion of the HTML content. In my case, I need to trigger click events on the document ...

The requested path /releases/add cannot be located

In my CRUD application, I have a feature that allows users to create releases by adding a version and description. This is achieved through a button and input fields for the details. <button (click)="addRelease(version.value, description.value)" [d ...

What's preventing me from tapping on hyperlinks on my mobile device?

I'm currently working on a website (saulesinterjerai.lt) and everything seems to be functioning properly, except for the fact that on mobile devices, the links aren't clickable and instead navigates to other layers. How can I disable this behavio ...

Generate and delete dynamic iFrames through variable manipulation

I'm currently developing a landing page specifically for our pilots to conveniently access weather information before taking off. However, due to the limitations posed by our computer security measures, I can only utilize iframes to obtain the necessa ...

Unable to display PHP response in a div using AJAX - issue persisting

Hey there! I'm currently working on a project where I want the form submission to load a response into a div without refreshing the page. I've looked at various examples of ajax forms with PHP online, but haven't been able to solve my issue ...

Embed a service within an Angular 1.5 component

I'm struggling with initializing a test.service.js file from an angular1.5 component and I'm not entirely sure how to accomplish it. Below is the structure I have used for my angular components: var testComponent = { templateUrl: "app/compo ...

guide for interpreting a complex json structure

I'm attempting to extract data from a JSON file that has multiple layers, like the example below. - "petOwner": { "name":"John", "age":31, "pets":[ { "animal":"dog", "name":"Fido" }, ...

What is the process for rendering a React class component using React HashRouter and Apollo client?

I've run into an issue with my project that involves using only React class components and fetching data from an Apollo server. The problem I'm facing is that, in Chrome, only the Navbar.jsx component is rendering. Even when I navigate to one o ...

React Router's nested route causes a full page reload when navigating

I have been working on setting up nested routing in React Router and here is my code: import React from 'react'; import DefaultSwitch from './components/DefaultSwitch/DefaultSwitch'; import './scss/App.scss'; const App = () ...

Dynamic styling updates on page refresh in Next.js

There is a strange issue with my styling that I can't seem to figure out. I have a NavBar set to be 20vh in height and an image set to be 100% in width. However, whenever I refresh the page, the NavBar height decreases and the image width increases si ...

Using jQuery to swap out sections of a HTML tag

Similar Question: Use of jQuery for Modifying an HTML Tag? After extensive research, I have not come across a solution that fits my specific requirements. My objective is to replace a part of an HTML tag without completely replacing the entire tag. To ...

What is the correct way to configure an API request utilizing the useEffect hook in React?

I have encountered an issue with my component where the correct data is showing up in the console under "data", but when attempting to run a map function on it, I am receiving an error message stating that "map is not a function." The console shows 16 item ...

What is the best way to maintain the toggleClass event state once an ajax call has been made?

If I have the HTML code below <div class="row"> <div class="link grey"> <a href="#">Link</a> </div> </div> <div class="row"> <div class="link"> <a href="#">Link</a> </div> & ...