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
Your code will throw an error because there is a typo
getDocs
from Firestore returns aQuerySnapshot
object, not an HTTP-like response object, soresponse.ok
condition is not relevant here.You just need a
try-catch
handling and it should work as expected: