I’m trying to fetch a specific document from firebase. If it exists, great. But if it doesn’t, I don’t want it to break my app. I just want it to move on. However, I can’t seem to shake off this error:
Here is my code:
JavaScript
x
11
11
1
async function getOtherInfo() {
2
//get profile image, username if they exist
3
4
const profileRef = doc(db, "profiles", email);
5
6
const snap = await getDoc(profileRef);
7
if (snap.exists()) {
8
setProfileImg(snap.data().profileImg);
9
setUserName(snap.data().userName);
10
}
11
Firebase gurus, please help me, I’m going crazy soon. Thanks a bunch.
edit: added code sections to show where my db and email state is coming from. Both are valid.
JavaScript
1
5
1
//init services
2
const db = getFirestore();
3
4
const [email, setEmail] = useState(identifier.email)
5
Advertisement
Answer
If think you’r looking for:
JavaScript
1
11
11
1
if (email) { // 👈
2
//get profile image, username if they exist
3
4
const profileRef = doc(db, "profiles", email);
5
6
const snap = await getDoc(profileRef);
7
if (snap.exists()) {
8
setProfileImg(snap.data().profileImg);
9
setUserName(snap.data().userName);
10
}
11
This ensure that you only try to load the document if there actually is an email
value.