I have user and group collections. Under the user collection, each document id is a user UID and each user document has an array field "userGroups" which contains the groups that user belongs to and those groups are the group's document ID under group collection.
I have been able to retrieve the userGroups array for the current user which i stored in groupRef (see code below). What I'm trying to do now is to map those array values into groups collection and retrieve only those documents that are in the groupRef. (Basically the goal is to just show in the UI the groups that the current user is a member of)
user collection group collection
const [groupsList, setGroupList] = useState([]);
const [groupRef, setGroupRef] = useState([]);
const [track, setTrack] = useState('')
const handleSubmit = () => {
setTrack('start')
fire.firestore().collection('users').doc(fire.auth().currentUser.uid).get().then((value) => {
console.log("userGroups " + value.data().userGroups) // this returns an object
setGroupRef([value.data().userGroups])
})
}
useEffect(() => {
handleSubmit()
}, [track])
console.log("sample list " + groupRef)
fire.firestore().collection('groups').onSnapshot(snapshot => (
setGroupList(snapshot.docs.map(doc => doc.data()))
))
^ this returns all the documents under groups collection. any ideas how i can retrieve only those that the current user is a member of? any help would be much appreciated. (ive been stuck on this for a long time. im also new to firebase.)
@DougStevenson directed me to the right path of using array-contains which is a helper function on querying/getting data. the code below is the answer to my problem. this way is shorter and more efficient than the work i came up with.
fire.firestore().collection('groups').where("groupMembers", "array-contains", fire.auth().currentUser.uid).onSnapshot(snapshot => ( setGroupList(snapshot.docs.map(doc => doc.data()))
))