Erjon
Erjon

Reputation: 930

Firebase Cloud Functions Object possibly 'undefined'

I have the following code in typescript and i get this error on the line: change.after.data();, Object is posibbly 'undefined':

import * as functions from 'firebase-functions'
import * as admin from 'firebase-admin'

admin.initializeApp()

export const onEditModeUpdate = 
functions.firestore.document("Settings/ShiftsEditMode").onUpdate(change=> {
    const after = change.after.data();
    const payload = {
        data: {
            temp: String(after.temp),
            conditions: after.conditions
        }
    }
    return admin.messaging().sendToTopic("Settings/ShiftsEditMode", payload)
})

enter image description here what I want to do is to send to my app a notification whenever something in firestore changes, I followed the official documentation but I get the error, I think this has to do with node.js version. Any help, please?

Upvotes: 3

Views: 1187

Answers (2)

Doug Stevenson
Doug Stevenson

Reputation: 317808

Your change parameter is of type Change. If you click through to it in VSCode, you'll see it's definition here:

export declare class Change<T> {
    before?: T;
    after?: T;
    constructor(before?: T, after?: T);
}

Notice that its before and after properties are both optional, marked with a ? in the type. This means that it's possible that the values are undefined.

It's likely that your TypeScript config in tsconfig.json contains a line for "strict": true, which tells TypeScript not warn you whenever you try to access a property that could be undefined without explicitly checking it first. That's the error you're seeing here.

You have two options:

1) Remove that line from your tsconfig.json

2) Or check to see if it's defined first

if (change.after) {
    const after = change.after.data();
    const payload = {
        data: {
            temp: String(after.temp),
            conditions: after.conditions
        }
    }
    return admin.messaging().sendToTopic("Settings/ShiftsEditMode", payload)
}
else {
    return null;
}

Upvotes: 3

Richard
Richard

Reputation: 1046

If you look at the types for the onUpdate handler, the argument for change has 2 optional properties, after and before:

class Change<T> {
    before?: T;
    after?: T;
    constructor(before?: T, after?: T);
}

Because you want to access after, you'll need to wrap it in a conditional, something like this following:

functions.firestore.document("Settings/ShiftsEditMode").onUpdate(change=> {
    if (change.after) {
        const after = change.after.data();
        ...
    }
}

Upvotes: 2

Related Questions