I have a custom hook called useDocument.js below which fetches the data from a firestore collection via a specific ID. Why is it that it’s returning [object Object] instead of plain object.
I’ve tried accessing the name property and logging it to the console using document.name but throws up an error:
Uncaught TypeError: Cannot read properties of null (reading ‘name’)
But when I use JSON.stringify(document), I can see the object properties and values
from documents 2: {“name”:”Mark Dave Marquez”,”id”:”D68ogPwGLCeaOfoRZIBe”}
Home.js
import React from "react";
import { Link } from "react-router-dom";
import { useAuthContext } from "../../hooks/useAuthContext";
import { useDocument } from "../../hooks/useDocument";
//components
import UserProfile from "../../components/UserProfile";
const Home = () => {
const { document, error } = useDocument("test", "D68ogPwGLCeaOfoRZIBe");
console.log("documents 2: " + document);
return <div> Test </div>
};
export default Home;
useDocument.js
import { useEffect, useState } from "react";
import { projectFirestore } from "../firebase/config";
export const useDocument = (collection, id) => {
const [document, setDocument] = useState(null);
const [error, setError] = useState(null);
// realtime document data
useEffect(() => {
const ref = projectFirestore.collection(collection).doc(id);
const unsubscribe = ref.onSnapshot(
(snapshot) => {
// need to make sure the doc exists & has data
if (snapshot.data()) {
setDocument({ snapshot.data(), id: snapshot.id });
setError(null);
} else {
setError("No such document exists");
}
},
(err) => {
console.log(err.message);
setError("failed to get document");
}
);
// unsubscribe on unmount
return () => unsubscribe();
}, [collection, id]);
return { document, error };
};
From the collection:
Advertisement
Answer
Nevermind, this is because of the way I use console.log("documents 2: " + document);
Forgot that the + sign converts the object into string thus the output would become [object Object].