Leverage VueJS and VueX to seamlessly integrate firebase 9 functions within my application

I am currently in the process of developing a blog application using Firebase version 9, VueJs version 3, and VueX. All functionalities such as user registration and authentication are working smoothly. However, I encountered an error when attempting to assign a user as an Admin using Firebase functions, and I'm unsure of the reason behind this issue. The specific error message I am receiving is shown below: https://i.sstatic.net/m0gTw.png

Upon removing the error catch block, a different error arises: https://i.sstatic.net/pZpID.png

I would greatly appreciate any assistance with resolving this matter.

According to the documentation provided at https://firebase.google.com/docs/functions/callable, it is mentioned that the functions need to be initialized as follows: This initialization process takes place in the firebaseInit.js file

// Necessary SDK imports
import { initializeApp } from "firebase/app";
import {
    getFirestore, 
} from "firebase/firestore"
import { getFunctions } from 'firebase/functions';

// Configuration for web app's Firebase settings
const firebaseConfig = {
  apiKey: "###",
  authDomain: "###",
  projectId: "###",
  storageBucket: "###",
  messagingSenderId: "###",
  appId: "###"
};

// Initializing Firebase and Functions
const app = initializeApp(firebaseConfig);
const functions = getFunctions(app);

// Service initialization
const db = getFirestore(app);

export { functions }
export default db;

In the Admin view section where the Admin role is set, the function call is made as demonstrated below: This code snippet is extracted from the Admin.vue file

<template>
<div class="admin">
    <div class="container">
      <h2>Administration</h2>
      <div class="admin-info">
        <h2>Add Admin</h2>
        <div class="input">
          <input placeholder="Enter user email to make them an admin" type="text" id="addAdmins" v-model="adminEmail" />
        </div>
        <span>{{ this.functionMsg }}</span>
        <button @click="addAdmin" class="button">Submit</button>
      </div>
    </div>
  </div>
</template>

<script>
import { functions } from "../firebase/firebaseInit"
import { getFunctions, httpsCallable } from "firebase/functions"

export default {
    name: "Admin",
    data() {
        return {
            adminEmail: "",
            functionMsg: null
        }
    },
    methods: {
        async addAdmin() {
          const functions = getFunctions();
          const setAdminRole = await httpsCallable(functions, "addAdminRole");
          setAdminRole({ email: this.adminEmail })
          .then((result) => {
            const data = result.data;
            this.functionMsg = data.message;
          })
          .catch((error) => {
            // Retrieving Error details.
            const code = error.code;
            const message = error.message;
            const details = error.details;
            console.log(code);
            console.log(message);
            console.log(details);
          });
        }
    }
}
</script>

The following Callable Cloud Function has been deployed on Firebase functions services in the index.js file:


const functions = require("firebase-functions");

// Required Firebase Admin SDK for Firestore access
const admin = require("firebase-admin");
admin.initializeApp();

exports.addAdminRole = functions.https.onCall((data, context) => {
    return admin.auth.getUserByEmail(data.email)
    .then((user) => {
        return admin.auth().setCustomUserClaims(user.uid, {
            admin: true
        });
    }).then(() => {
        return {
            message: `Success! ${ data.email } has been made an admin!!`
        }
    })
    .catch((err) => {
        console.log(err.message);
    });
});

Answer №1

It is advised not to do the following in your component:

import { functions } from "../firebase/firebaseInit"
import { getFunctions, httpsCallable } from "firebase/functions"

// ...

async addAdmin() {
  const functions = getFunctions();
  const setAdminRole = await httpsCallable(functions, "addAdminRole");
  setAdminRole({ email: this.adminEmail })
  ....   

Rather, you should just do:

import { functions } from "../firebase/firebaseInit"
import { httpsCallable } from "firebase/functions"

// ...

async addAdmin() {
  const setAdminRole = await httpsCallable(functions, "addAdminRole");
  setAdminRole({ email: this.adminEmail })
  ....  

This simplifies things since functions is exported in your firebaseInit.js file.

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

Local variables in AngularJS across multiple Angular applications

Looking for a method to retain a local variable not affected by path or angular app changes. Attempted using $window.localStorage.set and get item, rootScope, and $window.variable with no success. ...

TypeScript: creating an interface property that relies on the value of another

Is it feasible to have an interface property that relies on another? For instance, consider the following: const object = { foo: 'hello', bar: { hello: '123', }, } I wish to ensure that the key in bar corresponds to the value of f ...

Is it possible to generate a form dynamically in a Vue.js HTML file based on JSON data? Check out the provided f

Currently, I am diving into the world of vue.js and experimenting with building a dynamically created form. To explain further, I have JSON files that define what input types should be included in the form; now I am figuring out how to implement this usin ...

Collecting data from an HTML form filled out by users

I need a way to capture user input from an HTML form and display it later on my website. I want to show all the information users provide along with their pizza selections. I've been struggling for hours trying to make this work without success :( Spe ...

Creating a box that is connected by lines using JSON data requires several steps. You

I am attempting to dynamically draw a line using the provided JSON data. I have heard that this can be easily achieved with flexbox. Important: I would greatly appreciate a solution involving flexbox This is what I hope to achieve: https://i.stack.imgu ...

Tips for accessing a unique window name in JavaScript

How can I make window.name persist between page refreshes? I need to use window.name to differentiate between multiple browser windows, allowing each one to display distinct data while sharing the same URL. However, my problem is that the value of window ...

Embed HTML code into a React/Next.js website

I've been given the task of enhancing the UI/UX for an external service built on React (Next.js). The company has informed me that they only allow customization through a JavaScript text editor and injecting changes there. However, I'm having tro ...

React - Effective Ways to Update State Following an AJAX Call

I'm currently in the process of transitioning one page within my web application from using jQuery and Vanilla JS to utilizing React. However, I'm facing some challenges as React is still relatively new to me. On this particular page, I have an ...

Enhancing the structure and authentication of license plates

I'm having trouble figuring out how to apply Javascript to the text area. Can you advise on whether it's best to use onfocus, onblur, or onclick? Here is the code for the text area: <input type="text" name="c_Kenteken" id="invoerKenteken" cl ...

What is the best way to display a loader when utilizing AJAX with jQuery?

I am having trouble implementing a loader in my ajax jQuery call. My goal is to display a loader while the ajax request is fetching data from an API and hide it once the request is completed. I have split this functionality into 2 separate JavaScript fil ...

Text that appears automatically in an input field

I've searched high and low, but I just can't seem to find a solution that works for me. What I need is a way to automatically populate a HTML text field with default text when the page loads. This default text should ideally be a PHP variable and ...

How can I remove ASCII characters from an ajax response?

Experimenting with the API found at , but encountered an issue with properly formatting the received string. The string looks like this: Communication that doesn&#8217;t take a chance doesn&#8217;t stand a chance. The original response includes a ...

Leveraging the back button in an AngularJS Mobile SPA

Utilizing AngularJS for my Single Page App (SPA), I am currently exploring the most effective way to handle the back button functionality on mobile devices. My setup involves a single JavaScript file, one HTML page, and no partials. The content is reveale ...

Storing information within a Express application using Postgres

Recently, I've been delving into the world of Express and experimenting with a program that allows users to create events and invite others. While I know about using join tables to retrieve data, I'm curious if there's a way to organize the ...

Encountering the error message "ReferenceError: parsePayload cannot be accessed before initialization"

Check out this code snippet: Experiencing an issue with 'ReferenceError: Cannot access 'parsePayload' before initialization' Any assistance would be appreciated const express = require("express"); const { createToDo, updateToD ...

Update Refresh Token within Interceptor prior to sending request

I'm stuck on this problem and could use some guidance. My goal is to refresh a user's access token when it is close to expiration. The authService.isUserLoggedIn() function returns a promise that checks if the user is logged in. If not, the user ...

The child_process in Node is attempting to utilize /usr/bin/zsh, but unfortunately, it is unable to do so because

Recently, I've been encountering issues with several npm commands failing, accompanied by an error message that looks like this: npm ERR! code ELIFECYCLE npm ERR! syscall spawn /usr/bin/zsh npm ERR! file /usr/bin/zsh npm ERR! path /usr/bin/zsh npm ER ...

It appears that the SignalR proxy is not defined

Why is $.connection.connectionhub showing as undefined? I am using webform. <script src="/scripts/jquery-1.6.4.min.js"></script> <!--Reference the SignalR library. --> <script src="/scripts/jquery.signalR-2.2.1.min.js">< ...

Attaching a click event to a nested element within an AngularJS directive

I am currently working with the following directive. (function () { 'use strict'; angular.module('ap.App') .directive('clearCancelFinishButtonsHtml', function () { return { scope: { ...

Exploring the Use of 7BitEncodedInt in JavaScript

Currently, I am trying to read a binary file using JavaScript. It appears that this file may have been written in C#, which handles strings differently from how it's done in the source mentioned at https://learn.microsoft.com/en-us/dotnet/api/system. ...