I’m trying to get a user document from Firebase, in order to put it as a global variable in re-use it in some functions. One of them is displaySavedPlaces()
which allows to get a list of all the “places” documents the user has bookmarked. This is stored as an array of references in Firebase. Here is how it looks:
I store everything during onAuthStateChanged()
: I get the document related to the user uid, and I store it in a variable called currentUser
, also with user uid and a reference to the document if I need to call it again:
onAuthStateChanged(auth, async (userFirebase) => {
if (userFirebase) {
const userRef = doc(db, "users", userFirebase.uid);
const userDoc = await getDoc(userRef);
const userData = userDoc.data();
currentUser = { uid: userDoc.id, ...userData, ref: userRef };
const avatarRef = ref(avatarsImageRef, currentUser.customAvatar ?? "default-av.webp");
currentUser.avatarUrl = await getDownloadURL(avatarRef);
}
});
Then when I’m doing my function displaySavedPlaces
later, I have an error from Firebase: Type does not match the expected instance. Did you pass a reference from a different Firestore SDK?
It comes from the getDoc()
function.
async function displaySavedPlaces(user) {
console.log(user);
elements.savedPlacesContainer.innerHTML = "";
user.savedPlaces.forEach(async (elem) => {
console.log(elem);
const placeSnapshot = await getDoc(elem);
const place = placeSnapshot.data();
...
});
}
I was able to debug it by passing the saved places in a different variable than inside currentUser
. The references seems to be lost/affected during the currentUser variable filling. It’s happening also when I’m simply doing currentUser = userData
without creating any new object. Any idea why?