I'm attempting to check if a user is already stored in local storage before fetching it from the database:
async getQuestion(id: string): Promise<Question> {
let res: Question
await this.db.collection("questions").doc(id).ref.get().then(async function (doc: any) {
if (doc.exists) {
res = doc.data() as Question
res.from = this.authService.userCache(doc.data().from.id).then((data: User) => { return data as User }) <---- here
res.to = this.authService.userCache(doc.data().to.id).then((data: User) => { return data as User }) <---- and here
} else {
console.warn("There is no document for id " + id + "!");
res = null;
}
}).catch(function (error) {
console.warn("There was an error getting your document:", error);
res = null;
});
return res;
}
My userCache() function looks like this:
userCache(id : string): Promise<User> {
if (localStorage.getItem(id)) {
console.log("User found in cache")
return Promise.resolve(JSON.parse(localStorage.getItem(id)))
} else {
console.log("User not found in cache. Caching...")
return this.getSingleUser(id).then((user) => {
localStorage.setItem(id, JSON.stringify(user))
console.log("User cached")
console.log("User: " + JSON.stringify(user))
return user
}).catch(err => {
console.warn(err)
return null
})
}
}
However, I keep encountering the error:
TypeError: Cannot read properties of undefined (reading 'authService')
What might be causing this issue?