When the app directly calls cloud functions, it results in a return of null

My goal is to incorporate Firebase cloud functions into my app for posting user emails and names to a Firestore collection with randomly generated IDs. While everything seems to be functioning properly, I am facing an issue in receiving a response from the function back to my app. Below is the snippet of code from my app where I invoke the cloud function:

onPress ({commit, dispatch}, payload) {
      var addUserInformation = firebase.functions().httpsCallable('addUserInformation');
      addUserInformation(payload)
      .then(function(result) {
        console.log(result)
      }).catch(function(error) {
        var code = error.code;
        var message = error.message;
        var details = error.details;
        console.log(code);
        console.log(message);
        console.log(details);
      });
    },

And here's the implementation of the cloud function:

    const functions = require('firebase-functions')
const admin = require('firebase-admin');

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

// // Create and Deploy Your First Cloud Functions
// // https://firebase.google.com/docs/functions/write-firebase-functions
//


exports.addUserInformation = functions.https.onCall((data) => {
    admin.firestore().collection('Backend').where('email', '==', data[1]).get()
    .then(function(querySnapshot) {
            if (querySnapshot.size > 0) {
                console.log('Email already exists')
            } else {
                admin.firestore().collection('Backend').add({
                    name: data[0],
                    email: data[1]
                })
                console.log('New document has been written')
            }
        return {result: 'An outcome goes here'};
    })
    .catch(function(error) {
        console.error("Error adding document: ", error);
    })
});

The console displays that the result is null

Answer №1

Your Cloud Functions code is missing a promise return at the top level, causing it to end without sending any response back to the caller.

To resolve this issue, make sure to return the result of the top-level function:

exports.addUserInformation = functions.https.onCall((data) => {
    return admin.firestore().collection('Backend').where('email', '==', data[1]).get()
    .then(function(querySnapshot) {
            if (querySnapshot.size > 0) {
                console.log('Email already exists')
            } else {
                admin.firestore().collection('Backend').add({
                    name: data[0],
                    email: data[1]
                })
                console.log('New document has been written')
            }
        return {result: 'Successfully added user information'};
    })
    .catch(function(error) {
        console.error("Error adding document: ", error);
    })
});

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

What is the best way to create a dynamic text area that changes based on a dropdown selection?

I'm trying to create a feature on my form where selecting a retailer from a dropdown menu automatically generates a corresponding link next to the textbox. For example, if someone picks Best Buy, I want a link to bestbuy.com to show up immediately wit ...

Toggle the visibility of a div element and smoothly scroll to it on the page

Upon clicking the form, my goal is to show or hide it and scroll down to view the form. The current code I have in place seems to work after the first click. However, on the initial click, it shows the form but fails to scroll down. Any insights on what I ...

Analyzing the similarities in properties between two arrays of objects in order to generate a pair of fresh arrays

I have two sets of data represented as arrays: var oldOrder = [{"Id": "10","Qty": 1}, {"Id": "3","Qty": 2}, {"Id": "9","Qty": 2}]; var newOrder = [{"Id": & ...

What is the best way to showcase the reading from a stopwatch on my screen?

Working on these codes has been quite a challenge for me. I have recently embarked on a JavaScript journey as a beginner and attempted to create a stopwatch project. However, it seems like I may have missed the mark with the logic or implementation somewhe ...

Detecting an unexpected stop in an upload stream using busboyLooking for signs of an

I am currently facing an issue with my file uploading process into mongodb. Everything works smoothly, but the problem arises when the connection is lost unexpectedly (due to client browser closure, poor internet connectivity, power outage, etc.). In suc ...

What is the best way to find the maximum and minimum values within a nested array in JavaScript?

I am looking to extract the highest and lowest values from specific data points within a nested array. For example, this nested array is structured as [latitude, longitude]. The specific nested array in question looks like this: [[40, 50], [50, 60], [60, ...

Include previous input as a "phantom" thumbnail to the slider element of type "range"

https://i.stack.imgur.com/JnuCN.png Using a tutorial from w3schools, I have customized a regular range slider. The objective is to send a new value command to an external MQTT-based home automation system and display the previous value as a ghost-thumb in ...

Body-Processing Protocol

When I send a cURL POST request, it looks like this: curl http://tarvos.local:8080/partial_Users/2 -d '{currentPage : 1, firstID : 53d62fc6642aecf45c8b456f }' Within my NodeJS application, the request passes through the bodyParser.json() middl ...

Utilize separate CSS files in React components for better organization

Hello, I have encountered an issue with splitting my components and using react-router-dom. I decided to split the CSS for each component, such as Main.jsx - Main.css and CustomerBase.jsx - customerbase.css. However, the problem I am facing is that the CSS ...

Adjust parent div size based on image size increase

I am currently facing a situation where I have a page displaying an image, but sometimes it appears too small. In order to make the image larger, I have utilized CSS Transform and it is working well. However, the issue lies in the fact that the parent DIV ...

Utilizing jQuery's draggable() feature within a dynamic and adaptive layout…

Currently, I am tackling a standard image "reveal" effect utilizing jQuery UI’s draggable() feature. However, I am facing significant challenges in ensuring its functionality within a responsive design: http://codepen.io/ProfessorSamoff/pen/qEaNMM Whil ...

What are the steps for running a separate version of the selected_process and outdated_process?

Here's the code I've written to combine two history components into one. I'm using an if-else loop to achieve this, and it seems to be working fine. However, both icons end up showing all outdated processes. useEffect(() => { getVers ...

Organizing Results into Divs Based on Column Value Using AngularJs

I've been racking my brain trying to figure out the best way to organize and display my results in separate divs, specifically using Bootstrap col-md-4's. This is for a chat messaging app that I'm in the process of developing. I have rooms a ...

What is the process for declaring a member variable as an extended type in TypeScript?

Is it possible to declare a "member variable" as an "extension object" rather than a static type (without relying on an interface)? Imagine something like this pseudocode: class Foo { bar -> extends Rectangle; constructor(barInstance:IRec ...

I am having difficulty with the fadeIn animation not working as expected in my situation

http://jsfiddle.net/9w0v62fa/1/ Instead of using opacity 0 and 1 in two different places, which I find redundant, I attempted to utilize the CSS animate property. However, I couldn't get it to work. Here is my code: .btn{ background:blue; pa ...

Deleting an item using jQuery

In the Document Object Model (DOM), there is a button available to remove the parent element here: <i class="fa fa-times remove-product-compare" aria-hidden="true"></i> Here is an example of my DOM structure: <div class="col-lg-12 col-md- ...

Breaking down and analyzing XML information

I have data that I need to retrieve from an XML file, split the result, parse it, and display it in an HTML element. Here is a snippet of the XML file: <Root> <Foo> <Bar> <BarType>Green</BarType> &l ...

Updating a key in an array of objects with Mongoose in real-time

Although this question may have come up before, I haven't been able to find a solution that works. Essentially, I have an array of objects containing Boolean data and I want to be able to update these objects dynamically using my API routes/logic. D ...

Can we accurately pinpoint individual LineSegments in three.js by hovering over them, especially those with unique geometries?

Creating two examples of drawing lines in three.js was quite a fun challenge. One example showcased different geometry and material, while the other kept it simple with just one geometry and material. The demonstration links can be found here: Example 1 an ...

Allow React to complete one loop (including setState) before starting another loop

handleSubmit = () => { this.setState({ modalState: false }) this.state.codeToClass.forEach((code, classId, map) => { const cr = _.find(this.state.classRoles, { id: classId }) if (code === cr.classCode) { console.log(&apo ...