I have a simple function that checks if the user has Premium access or not:
JavaScript
x
16
16
1
export const checkPremium = async () =>{
2
if (auth.currentUser) {
3
const q = query(collection(db_firestore, 'users'));
4
onSnapshot(q, (querySnapshot) => {
5
querySnapshot.forEach((doc) => {
6
if (doc.id === auth.currentUser.uid) {
7
return doc.data().userSettings.hasPremium
8
}
9
});
10
})
11
}
12
else{
13
return false
14
}
15
}
16
I tried to catch this in various ways, but no luck, it always returns an “undefined” object.
JavaScript
1
10
10
1
const getPremium = async => {
2
checkPremium.then((response) => console.log(response))
3
}
4
5
const getPremium = async => {
6
let hasPremium = await checkPremium()
7
}
8
9
let hasPremium = checkPremium()
10
What is the correct way to get the returned Boolean value?
Advertisement
Answer
onSnapshot
is meant for listening to a collection continuously, getting repeatedly notified as its value changes. It does not create a promise, so the promise returned by getPremium is unrelated to the data you will eventually get in onSnapshot. If you just want to get the value once, you should use getDocs
:
JavaScript
1
16
16
1
export const checkPremium = async () =>{
2
if (auth.currentUser) {
3
const q = query(collection(db_firestore, 'users'));
4
const querySnapshot = await getDocs(q);
5
const match = querySnapshot.docs.find(doc => doc.id === auth.currentUser.uid);
6
if (match) {
7
return doc.data().userSettings.hasPremium);
8
} else {
9
return false;
10
}
11
}
12
else{
13
return false
14
}
15
}
16
Also, instead of getting all the users and then using client side code to find the one with the right id, you could just fetch that individual doc directly:
JavaScript
1
9
1
const ref = doc(db_firestore, 'users', auth.currentUser.uid)
2
const snapshot = await getDoc(ref);
3
const data = snapshot.data();
4
if (data) {
5
return data.userSettings.hasPremium
6
} else {
7
return false
8
}
9