Home > Net >  Fetch posts for users with a given ID in Firebase & Reactjs
Fetch posts for users with a given ID in Firebase & Reactjs

Time:09-08

I have been trying to fetch posts from Firestore for users with a given ID in Reactjs but no success. I keep getting this error from console;

App.js:64 Uncaught (in promise) TypeError: (0 , firebase_firestore__WEBPACK_IMPORTED_MODULE_12__.getDocs)(...).where is not a function
    at getPost (App.js:64:1)
    at App.js:69:1
    at invokePassiveEffectCreate (react-dom.development.js:23487:1)
    at HTMLUnknownElement.callCallback (react-dom.development.js:3945:1)
    at Object.invokeGuardedCallbackDev (react-dom.development.js:3994:1)
    at invokeGuardedCallback (react-dom.development.js:4056:1)
    at flushPassiveEffectsImpl (react-dom.development.js:23574:1)
    at unstable_runWithPriority (scheduler.development.js:468:1)
    at runWithPriority$1 (react-dom.development.js:11276:1)
    at flushPassiveEffects (react-dom.development.js:23447:1)

Here is my code;

import React, { useEffect, useState } from 'react'
import { collection, getDocs } from "firebase/firestore";
import { db } from '../firebase-config'

const [posts, setPosts] = useState([])
const postRef = collection(db, "posts")

useEffect(() => {
  const getPost = async () => {
    const data = await getDocs(postRef)
    .where('userId', '==', '12345').orderBy("createdAt").get()
    setPosts(data.docs.map((doc) => ({ ...doc.data(), id: doc.id })));
  };

  getPost();
}, []);

My firebase-config.js looks like this;

import { initializeApp } from "firebase/app";
import { getFirestore } from "@firebase/firestore"

const firebaseConfig = {
  apiKey: "xzy",
  authDomain: "xzy",
  databaseURL: "xzy",
  projectId: "xzy",
  storageBucket: "xzy",
  messagingSenderId: "xzy",
  appId: "xzy",
};

const app = initializeApp(firebaseConfig)
export const db = getFirestore(app)

If I remove this statement, .where('userId', '==', '12345').orderBy("createdAt").get() It fetches all the posts from the database which is not what I want. I want to be able to fetch only posts that matches a specific ID.

Any help will be highly appreciated.

CodePudding user response:

You are using the new Firebase Modular SDK that uses a functional syntax instead of the older namespaced one. You now need to use the top-level function query() to build a Query and other QueryConstraints like where, orderBy, limit are also functions. Try refactoring the code as shown below:

import { collection, getDocs, query, where } from "firebase/firestore"

useEffect(() => {
  const getPost = async () => {
    const q = query(postRef, where("userId", "==", "12345"));
    const data = await getDocs(q)

    setPosts(data.docs.map((doc) => ({
      ...doc.data(),
      id: doc.id
    })));
  };

  getPost();
}, []);

Also checkout: Firestore: What's the pattern for adding new data in Web v9? and the documentation that includes examples with both the syntaxes.

  • Related