Next.js Discord

Discord Forum

fetch data in server components with app directory.

Unanswered
ABUL KALAM posted this in #help-forum
Open in Discord
Here I have a function to fetch projects.
import { getDocs, collection } from "firebase/firestore";
import { db } from "../firebase";
const fetchAllProjects = async () => {
  try {
    const querySnapshot = await getDocs(collection(db, "Project"));
    if (!querySnapshot.empty) {
      const allProjects = [];
      querySnapshot.forEach((doc) => {
        const documentData = doc.data();
        allProjects.push({ id: doc.id, data: documentData });
      });
      return allProjects;
    } else {
      console.error("No Projects Found in the DB");
      return [];
    }
  } catch (error) {
    console.error("Error fetching Projects from DB:", error);
    return [];
  }
};
export default fetchAllProjects;

I want to fetch the projects here in page.js. If I do this way, I get the error since I have used projects?.length at some places. Initially, I was doing it using useEffect() but that make the page.js a client component. Please let me know how to do this, keeping my component a server component.
const Projects = async () => {
  const projects = await fetchAllProjects();
   return (
      // displaying the projects
  );
}

0 Replies