Encountering issues while retrieving parameters from Firebase function

I am currently attempting to use the SendGrid API from a Firebase function to send a confirmation email.

The API itself is functioning properly, but I am encountering an issue where I am unable to retrieve the value of the child oncreate (as shown in the Firebase function log):

TypeError: Cannot read property 'participant_id' of undefined
    at exports.SendEmail.functions.database.ref.onCreate.event (/user_code/index.js:15:38)
    at Object.<anonymous> (/user_code/node_modules/firebase-functions/lib/cloud-functions.js:112:27)
    at next (native)
    at /user_code/node_modules/firebase-functions/lib/cloud-functions.js:28:71
    at __awaiter (/user_code/node_modules/firebase-functions/lib/cloud-functions.js:24:12)
    at cloudFunction (/user_code/node_modules/firebase-functions/lib/cloud-functions.js:82:36)
    at /var/tmp/worker/worker.js:716:24
    at process._tickDomainCallback (internal/process/next_tick.js:135:7)

Here is the code snippet causing the issue:

const functions = require('firebase-functions');
const admin = require('firebase-admin');
admin.initializeApp(functions.config().firebase);

const SENDGRID_API_KEY = functions.config().sendgrid.key;

const sgMail = require('@sendgrid/mail');
sgMail.setApiKey(SENDGRID_API_KEY);

exports.SendEmail = functions.database.ref('participants/{participant_id}').onCreate(event => {


  const participant_id = event.params.participant_id;

  const db = admin.database();

  return db.ref(`participants/${participant_id}`).once('value').then(function(data){

    const user = data.val();

    const email = {
      to: user.email,
      from: '<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="fd8f989e8f88899890989389d39e948e8e8e9098cccbbd8e8e8e8ed39a92888bd38c9ed39e9c">[email protected]</a>',
      subject: "Bienvenue au Blitz d'embauche 2018!",

      templateId: 'dd3c9553-5e92-4054-8919-c47f15d3ecf6',
      substitutionWrappers: ['<%', '%>'],
      substitutions: {
        name: user.name,
        num: user.num
      }
    };

    return sgMail.send(email)
  })
  .then(() => console.log('email sent to', user.email))
  .catch(err => console.log(err))

});

I have worked with Firebase functions before and even used codes that were previously successful. However, I am still getting an undefined value!

Could the issue be related to any changes made by Firebase to event.params?

Additionally, my participant_id is an integer value (e.g., 3827). Could this be impacting the functionality?

Thank you for your assistance!

Answer №1

The function's signature is incorrect, you can refer to this example from Handling event data:

exports.convertToUpperCase = functions.database.ref('/messages/{pushId}/original')
    .onCreate((snapshot, context) => {
        console.log('Converting to uppercase', context.params.pushId, original);
    });

Just make the necessary adjustment to your onCreate function and everything will work smoothly :)

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

Issue with jsPDF: PNG file is either incomplete or corrupted

I'm encountering an issue while attempting to pass Image data to the addImage function. I have tried downgrading the versions of jspdf and html2canvas, as well as experimenting with different ways to import the two libraries, but the problem still per ...

How to utilize Angular JS for excluding numbers contained within parentheses

I am working with JSON data that looks like this: [{name:"abc", count:"(10)", {name:"xyz", count:"(20)"}, {name:"pqr", count:20}] To display this data, I am utilizing Angular datatables and now I am looking to sort the count column in a specific way. U ...

What is the best way to programmatically insert a new element into the DOM after it has already been rendered in Next

In my project with Next.JS 13, I am currently exploring methods to manually inject component code into an existing element in the DOM that has already been rendered. Below is the code snippet for the component: const layouts = { forgotPassword: () => ...

Calling Ajax inside each iteration loop

I have encountered numerous posts discussing this topic, but the solutions I came across do not quite suit my needs. Some experts suggest changing the code structure, however, I am unsure of how to go about doing that. What I desire: 1) Retrieve a list ...

Is it possible to utilize axios in Vue while utilizing CORS in the API?

I am encountering an issue with making a GET request to a CORS enabled corona virus API using axios and Vue. I have no control over their server, and my Vue app was created with vue-cli. Interestingly, I am able to make two requests from different APIs - ...

The data from the AJAX response is not appearing on the HTML table within the modal using jQuery

I have a link that, when clicked, opens the modal and calls the ajax method. The modal opens and the ajax method retrieves the response data successfully, but the data is not displayed within the table on my modal. I have tried multiple approaches, but non ...

Leveraging Socket.IO server and client on separate subdomains

I currently have two subdomains set up for my domain: socket.mydomain.com - This is where the Socket.IO server is located app.mydomain.com - A web application that I want to connect to my WebSocket server. On the landing page of app.mydomain.com, I have ...

When a page with parameters is reloaded, React fails to initiate

I'm encountering an issue with my application in development mode on localhost. When I try to reload the app on a route with parameters, for example: localhost:8080/item/2 React fails to initialize and only a blank page is displayed. However, if I ...

Issues arise with objects disappearing when zooming out in Three.js

In my current three.js project, I have encountered an issue with the z position of my camera. Whenever the z position is set too high, the scene turns completely black when zooming out, which is not the desired outcome. Specifically, with camera.position. ...

Click function unresponsive following the completion of an Ajax call

I'm having an issue with my WordPress site where the JavaScript code I am using for an Ajax filter is not functioning properly once the filter is activated. Specifically, the click event is not working as expected. function addStoreLinkListeners() { ...

Unable to get Angular ng-click to function properly when used in conjunction with $

I am encountering an issue with triggering a click event in my Angular app using code similar to the example below. Can anyone help me understand why the event is not being triggered? var app = angular.module("myApp", []) app.directive('myTop', ...

The presence of asynchronous JavaScript can lead to errors due to missing functions in JavaScript

I've encountered an issue with a jQuery script that I modified by adding an ASYNC attribute. Surprisingly, it functions correctly in Firefox but encounters intermittent failures in both Chrome and IE browsers. Here's the PHP code snippet respons ...

Navigate user to the designated page once they have successfully signed in

I'm relatively new to Angular, and my current focus is on configuring and testing all the routes to ensure they function properly. Setup: When a user navigates to specific pages (/settings in this instance), the application needs to verify if there i ...

Transform various tables enclosed in separate div elements into sortable and filterable tables

I'm encountering an issue with making multiple tables sortable and searchable on one page. Despite all the tables having the same class and ID, only the first table is responsive to sorting and searching. I've followed a tutorial that recommends ...

Unable to define custom headers in AngularJS

When making an HTTP GET call, I tried to set custom properties in the header but they are not showing up at the backend and aren't visible in the HTTP request. Here's the code snippet I used: app.controller("BranchController", function ($scope, ...

You are not allowed to have a union type as the parameter type for an index signature. If needed, consider using a mapped

I'm attempting to implement the following structure: enum Preference { FIRST = 'first', SECOND = 'second', THIRD = 'third' } interface PreferenceInfo { isTrue: boolean; infoString: string; } interface AllPref ...

Managing iframes in React using reference methods

Trying to set the content of an iframe within a React component can be a bit tricky. There is a component that contains a handleStatementPrint function which needs to be called when the iframe finishes loading. The goal is to print the loaded iframe conten ...

Encountering an error with Next.JS when using the "use client" directive

Recently encountered a bizarre issue with my next.js project. Every time I input "use client"; on a page, it triggers a "SyntaxError: Unexpected token u in JSON at position 0". Here's the code snippet for reference: "use client" ...

Node.js CallbackHandler: Simplifying event handling in JavaScript applications

I implemented the following function in a .js file to handle an asynchronous network connection: function requestWatsonDiscovery(queryString) { console.log('Query =', queryString); if (typeof queryString !== 'undefined') { ...

Creating a loading spinner in a Bootstrap 5 modal while making an XMLHttpRequest

While working on a xmlhttprequest in JavaScript, I incorporated a bootstrap spinner within a modal to indicate loading. The modal toggles correctly, but I am struggling to hide it once the loading is complete. I prefer using vanilla JavaScript for this ta ...