skip to Main Content

This is from a react project with react-router and Firebase. I’m using react-router’s loader function for fetching some data from Firebase firestore. Instead of returning data, the loader function is throwing "Could not fetch projects" as is mentioned in the code below despite the config and read/write security rules being suitable. This obviously means that there’s come problem with the response but I don’t know how to fix the issue.

function Homepage() {
  return (
    <>
      <HeroSection />
      <FeaturedProjects />
    </>
  );
}

export default Homepage;

export async function loader() {
  const response = await getDocs(collection(db, "projects"));
  if (!response.ok) {
    return json({ message: "Could not fetch projects" }, { status: 500 });
  } else {
    return response;
  }
}

I’ve omitted irrelevant code but I’d be happy to share any other information/code needed to better assess the situation.

Update: getting rid of the if(!response.ok){...) block is solving the problem and the desired response is getting logged into the console.

2

Answers


  1. Your code will throw an error because there is a typo

    export async function loader() {
      const response = await getDocs(collection(db, "projects"));
      if (!response.ok) {
        return json({ message: "Could not fetch projects" }, { status: 500 });
      } else {
        return response;
      }t
    ---^--- t is not defined
    }
    
    Login or Signup to reply.
  2. getDocs from Firestore returns a QuerySnapshot object, not an HTTP-like response object, so response.ok condition is not relevant here.
    You just need a try-catch handling and it should work as expected:

    try {
      const querySnapshot = await getDocs(collection(db, "projects"));
      const projects = querySnapshot.docs.map(doc => doc.data());
      return { projects }; 
    } catch (error) {
      console.error("Error fetching projects:", error);
      throw new Error("Could not fetch projects"); 
    }
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search