Firebase function encountered an issue: The object may be undefined

My goal is to deploy a basic function on Firebase that sends notifications to subscribers when a new record is added to the 'todos' collection.

The token for the subscriber is:

evGBnI_klVQYSBIPMqJbx8:APA91bEV5xOEbPwF4vBJ7mHrOskCTpTRJx0cQrZ_uxa-QH8HLomXdSYixwRIvcA2AuBRh4B_2DDaY8hvj-TsFJG_Hb6LJt9sgbPrWkI-eo0Xtx2ZKttbIuja4NqajofmjgnubraIOb4_

I tried following a tutorial to achieve this, but I encountered an error during deployment.

Here is the code snippet of my function:

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

admin.initializeApp(functions.config().firebase);

exports.newSubscriberNotification = functions.firestore
.document('todos')
.onCreate(async event=>{
    const data = event.data();
    const workdesc = data.workdesc;
    const subscriber = "evGBnI_klVQYSBIPMqJbx8:APA91bEV5xOEbPwF4vBJ7mHrOskCTpTRJx0cQrZ_uxa-QH8HLomXdSYixwRIvcA2AuBRh4B_2DDaY8hvj-TsFJG_Hb6LJt9sgbPrWkI-eo0Xtx2ZKttbIuja4NqajofmjgnubraIOb4_";

// notification content
const payload = {
    notification: {
        title: 'new write in collection todos',
        body: workdesc,
       //body: 'body',
        icon: 'https://img.icons8.com/material/4ac144/256/user-male.png'
    }
}

// send notification
return admin.messaging().sendToDevice(subscriber, payload)

});

Error Details:

src/index.ts:11:11 - error TS6133: 'workdesc' is declared but its value is never read.

11     const workdesc = data.workdesc;
             ~~~~~~~~

src/index.ts:11:22 - error TS2532: Object is possibly 'undefined'.

11     const workdesc = data.workdesc;

Found 2 errors.

npm ERR! code ELIFECYCLE
npm ERR! errno 2
npm ERR! functions@ build: `tsc`
npm ERR! Exit status 2
npm ERR!
npm ERR! Failed at the functions@ build script.
npm ERR! This is probably not a problem with npm. There is likely additional logging output above.

Edit Update:

Even after making the suggested changes, I am still encountering a HTTP Error: 400 while deploying the function. Please refer to the attached screenshot for more information.

https://i.sstatic.net/cTvHz.png

Answer №1

The TypeScript errors you're seeing indicate that there are two issues at hand.

Firstly, the error is alerting you that you are attempting to access a property of an object that may be undefined, potentially leading to a crash. The `data` variable could indeed be undefined due to the function's signature. In the case of an onCreate function, it will never be defined, so you can use the `!` operator to explicitly inform TypeScript that it will always have a value:

    const data = event.data()!;

The second error points out that you have created a variable (`workdesc`) but never utilized it in your code. You can safely remove it as it serves no purpose unless you intend to use it in the future.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

How to prevent value overwriting when adding dynamic fields in Angular 7?

In my current project using Angular, I am tasked with setting up configuration using 4 specific fields: Department Name (select option) Service Name (select option) Status (text input) Level (text input). I need to be able to add multiple sets of these ...

The useForm function from react-hook-form is triggered each time a page is routed in Nextjs

Hey there, I'm just starting out with Next.js (v14) and I'm trying to create a multi-page form using react-hook-form. But I'm encountering an issue where the useForm function is being executed every time, and the defaultValues are being set ...

The nz-switch function is malfunctioning as a result of an update that has affected its value

<form [formGroup]="businessFoodHygieneForm"> <div class="box p-4 d-flex jc-between ai-center"> <span> Food Hygiene Link </span> <label> <nz-switch class="switch- ...

"Error message: TypeORM DataSource encounters a password issue with the client

Here is the content of my data-source.ts file: import {DataSource} from "typeorm"; import path from "path"; import {User} from "./entity/User"; import { config } from "dotenv"; config(); export const AppDataSource ...

An Array of objects is considered NULL if it does not contain any values before being iterated through

Working with Files in TypeScript (Angular 8) has led me to Encode the files in Base64 using the code below: private async convertToBase64(evidences: Array<EvidenceToDisplay>): Promise<Array<EvidenceToDownload>> { const results: Arr ...

Create a definition file containing a class that can be easily extended

I am attempting to define an interface in a declaration file: declare namespace Foo{ export interface Bar{ new(attrs, options) } } Then I want to inherit from this interface in my code: class Chunk extends Foo.Bar {} However, I encounte ...

Error encountered during module parsing: Token found was not as expected in Webpack 4

When I run my builds, webpack keeps throwing this error: ERROR in ./client/components/App/index.tsx 15:9 Module parse failed: Unexpected token (15:9) You may need an appropriate loader to handle this file type. | | > const App: SFC = () => ( ...

The type "AppRouterInstance" cannot be assigned to type "nextRouter"

Within my Next.js project, a registration form is included as seen below: "use client"; import * as React from "react"; import { zodResolver } from "@hookform/resolvers/zod"; import { useForm } from "react-hook-form" ...

Creating a versatile modal component with Angular for endless usage opportunities

After following this informative tutorial, I successfully created a flexible and customizable modal component. However, a new challenge has arisen. Consider two components, A and B, both utilizing the modal component to display modals. In Component A, I ne ...

You must add the module-alias/register to each file in order to use path aliases in

I am currently utilizing typescript v3.6.4 and have the following snippet in my tsconfig.json: "compilerOptions": { "moduleResolution": "node", "baseUrl": "./src", "paths": { "@config/*": ["config/*"], "@config": ["config"], ...

Setting up Firebase and Vue: Best practices for initializing Firebase and Vuefire

I am encountering an issue while setting up Vuefire and Firebase in my application. The error that I see in the console is: FirebaseError: Firebase: Firebase App named '[DEFAULT]' already exists (app/duplicate-app). at initializeApp (webpack ...

Utilizing the .add() method in Firebase Cloud Firestore for working with nested

In the documentation for Firebase, it mentions updating nested objects. You can find out more about this here: https://firebase.google.com/docs/firestore/manage-data/add-data#update_fields_in_nested_objects Here is my data structure: let ref = db.collect ...

What is the significance of the IRenderFunction interface definition in FluentUI?

Recently diving into TypeScript, I've begun working with DetailsList in Fluent UI. Check it out here: https://developer.microsoft.com/en-us/fluentui#/controls/web/detailslist. I'm exploring the onRenderRow property, which is of type IRenderFunct ...

Exploring Vue with Typescript - leveraging components without explicit definitions

Has anyone successfully used vue-instant component as a child component before? I'm having trouble adding components without definition. Could it be related to webpack config ignoring node_modules due to lack of type declaration? Here's the code ...

What is the correct way to express an object in an array?

I've encountered an issue: I'm working with an array called _daysConfig<DayConfig> When I manually populate it like this, everything functions correctly: _daysConfig: DayConfig[] = [ { date: new Date('Wed Jul 22 2020 21:06:00 GMT+02 ...

TS2339 Error: The 'scan' property cannot be found on the 'Observable<Message[]>' type

I am currently following a guide on creating a chatbot using Angular. I encountered the following error: ERROR in src/app/chat/chat-dialog/chat-dialog.component.ts(24,6): error TS2339: Property 'scan' does not exist on type 'Observable&apos ...

Is there a way to configure ESLint so that it strictly enforces either all imports to be on separate lines or all on a single line?

I am currently using ESLint for TypeScript linting. I want to set up ESLint in a way that requires imports to be either all on separate lines or all on a single line. Example of what is not allowed: import { a, b, c, d } from "letters"; Allo ...

Error: Unable to access 'useRef' property of null object due to TypeError

Currently, I am using a combination of Next.js, TypeScript, sanity, and tailwindcss in my project. I have come across an error while attempting to utilize the react-hook-form. I have experimented with different approaches: Converting the Post function in ...

In TypeScript, the Select element does not contain an options property

Having trouble iterating through a TypeScript array. Here are the methods I'm using: getNotification(evt: string, rowIndex: number) { console.log("Production order: law has changed to " + evt + " " + rowIndex); var select = document.getEleme ...

The console is displaying an undefined error for _co.photo, but the code is functioning properly without any issues

I am facing an issue with an Angular component. When I create my component with a selector, it functions as expected: it executes the httpget and renders a photo with a title. However, I am receiving two errors in the console: ERROR TypeError: "_co.photo ...