Home > OS >  TypeError: Cannot read properties of undefined (reading 'authService')
TypeError: Cannot read properties of undefined (reading 'authService')

Time:08-13

I'm trying to detect if a user is already saved in localstorage before reading 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() is 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. Cacheing...")
            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
            })
        }
    }

But I always get the error: TypeError: Cannot read properties of undefined (reading 'authService')

What could be the problem here?

CodePudding user response:

try arrow functions. Usually this is different for normal functions and arrow functions. arrow function will have this as the parent scope.

async getQuestion(id: string): Promise<Question> {
        let res: Question
        await this.db.collection("questions").doc(id).ref.get().then(async (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((error) => {
            console.warn("There was an error getting your document:", error);
            res = null;
        });
        return res;
    }
  • Related