Retrieve the user's unique identification number upon creation and proceed to update the database accordingly

I'm trying to create a cloud function that automatically adds 50 points to the "points" field in the database whenever a new user is created using the "onCreate((user)" function. The goal is to simply detect when a new user is created, retrieve their ID, and update their points to 50 using a cloud function. Here is what the setup looks like:

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

Below is the current code I have been working on:

    exports.updatepoints = functions.auth.user().onCreate((user) => {

  const userID = firebase.auth.currentUser.uid; 
  return updatepoints(userID)
});

async function updatepoints(userID) {
  return firebase.database().ref('mobile_user/' + userID).set(
    {
      points: 50
    });
};

I am new to JavaScript and Firebase, so any advice or guidance would be greatly appreciated.

Answer №1

If I were to tackle this, I would approach it like this:

First things first, I believe it's important to rename the function to accurately reflect its purpose. So, in this case, I would rename it to initUser, signifying that it is responsible for initializing a user.

Next, the function receives user data, which can be utilized to gather information about the user being created and then storing that data in Firebase.

Here is a potential solution:

import { auth } from 'firebase-functions';
import { database } from 'firebase-admin';

exports.initUser = functions.auth.user().onCreate((user) => {

const mobileUser = {
email: user.email,
points: 50,
subscribedToMailingList: true
}    

const ref = database().ref(`mobile_user/${user.uid}`);

  return ref.set(mobileUser)
    .then(() => console.log(`Created user: ${user.email}`))
    .catch((error) => console.log(`Error: ${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

Form validation errors were detected

Currently, I am working with a formgroup that contains input fields with validations set up in the following manner: <mat-form-field class="mat-width-98" appearance="outline"> <mat-label>Profession Oc ...

Refresh the div element's HTML and content using AJAX

I am interested in implementing a feature similar to the StackExchange link found on the top left of the Stack Overflow site. From what I gather, when the stack exchange link is clicked, the following actions take place: The hidden div container becom ...

Executing a function should be delayed until all necessary information is obtained from the REST Api

I want to create a chart showing data for each month over the course of 12 months. The data for each month will be retrieved from a REST API. Here is my approach: $.getJSON(link, function(data){ // store data in a variable } Repeat this process 12 t ...

window.onresize = function() { // code here

Here's an example of code I've been working on: $(document).ready(function (e) { adjustSize(); $(window).resize(adjustSize); function adjustSize() { var windowWidth = parseInt($(window).width()); if (windowWidth > ...

Prevent the onClick function of the outer div from being triggered by clicking on the inner div

Similar Question: Stop parent container click event from firing when hyperlink clicked My issue is <div onClick="someJScode();"> ... <div></div> ... </div> I need to prevent someJScode() from executing when the inner di ...

What is the best way to switch between light and dark themes with the ability to locally store the current theme?

Being new to the realm of react, I have been delving into the implementation of new features using Material-UI. One particular feature I am working on involves toggling between light and dark themes, with the current theme being stored locally within the b ...

Laravel 4 Data Cleaning for Improved Security

I am currently utilizing Laravel 4 to establish a RESTful interface for my AngularJS application. Right now, I am looking to update an object within my model named Discount Link. The method I am using involves: $data = Input::all(); $affectedRows ...

I encountered a ReferenceError stating that the variable "req" is not defined when I try to

I am currently developing a login application using React.js and Node.js (Express, JWT), but I am facing an issue when trying to export my function. I keep receiving the error ReferenceError: req is not defined, even though I have defined req. How can I re ...

Step-by-step guide on how to prioritize rendering the login page before the ngView in AngularJS in order to

As I begin my journey with Angular JS, I am eager to implement security measures in my application. My intention is to set up a log-in page as the default landing page for my single page application. Can anyone provide guidance or recommendations on how ...

Converting Emoji to PNG or JPG using Node.js - What's the Procedure?

Currently, I am working on a project that requires me to create an image file from emoji characters, preferably using Apple emoji. Initially, I thought this task would be simple to accomplish, but I have encountered obstacles with each tool I have tried. ...

The functionality of the JavaScript click function is limited to a single execution

In my dropdown menu, I have a submit function that triggers whenever any children of the dropdown are clicked. However, I now need to exclude a specific li element from this function because it requires inserting a tracking ID in a popup iFrame. The code ...

Conceal location labels in maps provided by tilehosting.com

I am currently in the initial stages of developing a maps web application and I want to incorporate maps from tilehosting.com along with the leaflet library (leafletjs.com). Overall, it seems to be working fine, but I'm struggling with hiding the def ...

jQuery deduct a value from a given value

i have a full duration that is divided into multiple sections, the user needs to input the duration for each section i would like the system to calculate and display the remaining duration from the full duration, regardless of whether the user fills out ...

Having trouble uploading the file to IPFS: Encounter an issue with HTTPError: project id is mandatory

Currently in the process of developing a basic DApp for sharing chats, with similarities to Twitter but based on a smart contract. I am utilizing hardhat and running my application on localhost. While implementing the feature for users to upload a profile ...

Unable to choose anything beyond the initial <td> tag containing dynamic content

Struggling to implement an onclick delete function on dynamically selected elements, but consistently encountering the issue of only selecting the first element each time. // Function for deleting entries $("#timesheet").on('click', &ap ...

ESLint version 8.0.0 encountered an error while attempting to fetch the '@typescript-eslint' plugin

Hey there, I'm in need of some assistance. I encountered an error while trying to build a project. Uh-oh! Something didn't go as planned! :( ESLint: 8.0.0 TypeError: Failed to load plugin '@typescript-eslint' specified in ' ...

JavaScript can be used to call a web service directly from a content page

Is there a way to call an autocomplete webservice from JavaScript in a content page that is part of the same web app? I have found that when I include a master page, the autocomplete feature stops working. I haven't added a script manager to the maste ...

Retrieving checkbox value upon form submission

Imagine having a form containing several checkboxes. Upon submitting the form, you aim to display all values of the selected checkboxes. <form> <input type="checkbox" id="product1" name="product1" value="12"> <input type="checkbox" id="prod ...

How can one deactivate a <MenuItem> component in material-ui?

Currently, I am in the process of developing a personalized combo box using React and Material-UI. This unique combo box will exhibit the chosen value within the input, present a drop-down menu with various options (MenuItems), and feature a text box at th ...

Displaying file when JQuery dialog is opened

I am utilizing a JQuery dialog to load a partial view within it. $("#WOdialog").dialog({ width: 765, resizable: false, closeOnEscape: true, modal: true, clos ...