Reputation: 112
I am Facing the Below Mentioned Error When Fetching Data from Firebase and Setting it to State Inside a useEffect
Hook.
Here is The Code i am Using With Simplified Markup:
function PostComponent({ id }){
const [post,setPost] = useState({});
const [error,setError] = useState("");
const db = firebase.firestore();
useEffect(()=>{
db.collection('posts').doc(id).get().then(doc=>{
setPost(doc.data());
}).catch(err=>setError(err.message));
}, []);
return (
{error && <h1>{ error }</h1>}
<PostCard data={post} />
);
}
Upvotes: 0
Views: 213
Reputation: 7388
Can you pls try it like this:
//this can be outsite of your component
const db = firebase.firestore();
function PostComponent({ id }){
const [post,setPost] = useState({});
const [error,setError] = useState("");
useEffect(()=>{
db.collection('posts').doc(id).get().then(doc=>{
setPost(doc.data());
}).catch(err=>setError(err.message));
}, [id]);
return (
{error && <h1>{ error }</h1>}
<PostCard data={post} />
);
}
If that doesn't work then the error is probably comming from another component.
Upvotes: 2