skip to Main Content

I have a users collection in which there are users based on ids, and each of them has a field called goal. I’d like to check if that goal field is empty or not in order to perform other actions/show other fields etc but I cannot figure out a way to do so.

What I am mostly confused about is the usage of the queries, I have found several different methods and none works, and I am not sure about all the updates and all.
I have the newest version of firebase, firestore and react.

My firebaseconfig:

    // v9 compat packages are API compatible with v8 code
import firebase from 'firebase/compat/app';
import 'firebase/compat/auth';
import 'firebase/compat/firestore';
import { getAuth } from "firebase/auth";
import { getFirestore } from "firebase/firestore";

// Your web app's Firebase configuration
const firebaseConfig = {
  ...
};

const firebaseApp = firebase.initializeApp(firebaseConfig);

export const auth = getAuth(firebaseApp);
export const db = getFirestore(firebaseApp);

export default firebaseApp;

An example of how I fetch data into a list:

const [goals, setGoals] = useState([]);

    const fetchPost = async () => {
       
        await getDocs(collection(db, "goals"))
            .then((querySnapshot)=>{               
                const newData = querySnapshot.docs
                    .map((doc) => ({...doc.data(), id:doc.id }));
                    setGoals(newData);                
                console.log(goals, newData);
            })
       
    }
    useEffect(() => {
        fetchPost();

      }, []);

This is what I have now:

let user = firebase.auth().currentUser;
    var userEmail = user.email;
    let userName = userEmail.match(/^([^@]*)@/)[1];
    let userId = user.id;
    const [currentGoal, setCurrentGoal] = useState([]);
    const fetchPost = async () => {
       
        await getDocs(collection(db, "users"))
            .then((querySnapshot)=>{               
                const newData = querySnapshot.docs
                    .map((doc) => ({...doc.data(), id:doc.id }));
                    if(doc.id === userId )
                        setCurrentGoal(newData);
                            
                console.log(currentGoal, newData);
            })
       
    }
    useEffect(() => {
        fetchPost();

      }, []);

But the problem is 1. the user id is not working (I don’t know how to use it in a query) and I am unsure how to get the information about the goal field.
Here is my collection to make it more clear:
collection

I have tried these practices but didn’t work:

  • db.collection("users").where("email", "==", usersEmail)
    .get() ……
  • the one tht starts with firestore(). … -> it says firestore is not defined

2

Answers


  1. If you’re asking how to query for the document ID in the v9 SDK, that’d be:

    const qry = query(collection(db, "users"), where(documentId(), "==", "valuetosearchfor"));
    const querySnapshot = getDocs(qry);
    ...
    

    Also see my answer here: Firestore – Web version 9 – get all documents in collection whose id is in array of ids

    Login or Signup to reply.
  2. You can use Object,hasOwnProperty("goal")) and doc.data().goal !== "") to check if the goal property exist or is empty as follows:

    import { query, collection, where, getDocs } from "firebase/firestore";
    import { useState, useEffect } from "react";
    import { auth, db } from "./config/firebase";
    
    export default function App() {
      const [currentGoal, setCurrentGoal] = useState("");
    
      useEffect(() => {
        const fetchPost = async () => {
          const user = auth.currentUser;
          const userId = user!.uid;
    
          const q = query(collection(db, "users"), where("id", "==", userId));
    
          const querySnapshot = await getDocs(q);
    
          const userData = querySnapshot.docs[0]?.data(); //getting the only user data
    
          if (userData.hasOwnProperty("goal") && userData.goal !== "") {
            const goal = userData.goal;
            setCurrentGoal(goal); //if goal exists and not empty set current goal
          } else {
            setCurrentGoal(""); //if goal not exists or empty set current goal as ""
          }
        };
    
        fetchPost();
      }, []);
    
      return (
        <div>
          <p>Current goal: {currentGoal}</p>
          {/* other code here */}
        </div>
      );
    }
    

    As from the details you shared it looks like you are storing the goals just as a string field. Hence why I have used currentGoal as a string property.

    Reference : Object.hasOwnProperty()

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search