I am new to React Native and Firebase and I am building an app using firestore.
the structure of firestore db looks like this :
AllPosts > Doc(each post) > Field(name,desc, .... , userId="12345")
and for users
users > doc(each user) id 12345 > field(name,desc,etc)
I don't know if this is the best way to setup the database. But when I go to a post screen, I need to load all data for that post & data for the userId who created the post, yet they are in entirely different collections.
I couldn't find a good way to do this. I've tried setting the userId field from post doc to a const 'fetchUserById' and perform a query based on that, but I think it's dead wrong
const [post, setPost] = useState([]);
const [user, setUser] = useState(null);
useEffect(() => {
firebase.firestore()
.collection("allPosts")
.where(firebase.firestore.FieldPath.documentId(), '==', props.route.params.postId)
.get()
.then((snapshot) => {
let data = snapshot.docs.map(doc => {
const data = doc.data();
const id = doc.id;
return { id, ...data }
})
setPost(data)
})
const fetchUserById = post.userId;
firebase.firestore()
.collection('users')
.where(fetchUserById, '==', firebase.firestore.FieldPath.documentId())
.get()
.then((snapshot) => {
if (snapshot.exists) {
setUser(snapshot.data());
}
else {
}
})
},[])