Sending variables through methods in Vue.js is not functioning as expected

I have a straightforward form that utilizes Vue.js with Firebase (specifically the package vue-firestore). I have methods to manage user registration in Firebase, change the displayName value, and log out the current user. After this, I am registering some fields in a Firestore. However, I am struggling to save the uid of the created user to store in Firestore, as I cannot access the value of the variable in the createProvider method.

Here is my Vue.js component:

import firebase from 'firebase/app';
import { db } from "../firebase";
import "firebase/auth";

export default {
  data: () => ({
    // item fields
    nameProvider:"",
    enderecoProvider:"",
    numeroProvider:"",
    cityProvider: "",
    distritoProvider: "",
    paisProvider:"",
    complementoProvider: "",
    telefoneProvider: "",
    nomeContatoProvider: "",
    emailProvider: "",
    passwordProvider: "",
    userId: "",
    userIdTemp: "",
  }),
  
  firestore() {
    return {
      users: db.collection("users"),
    };
  },

  methods: {
    signUp() {
      var that = this;
       firebase.auth().createUserWithEmailAndPassword(this.emailProvider, this.passwordProvider)
        .then((user) => {
          this.userId = user.user.uid;
          this.authState();
        })
        .catch((error) => {
          console.log("ERROR", error);
        });
    },
    
    authState() {
      var that = this;
      firebase.auth().onAuthStateChanged(function(user) {
          if (user) {
            user.updateProfile({
                displayName: "2",
              });
                firebase.auth().signOut().then(() =>{
                  that.$swal({
                      icon: "success",
                      title: "Provider created successfully",
                      text: "For security reasons, please log in again"
                    }).then((result) => {
                      if (result.isConfirmed) {
                        that.$router.replace('/');
                        location.reload();
                      }
                    })
                })
          console.log(user);
          } else {
            // No user is signed in.
          }
        });
    },

    createProvider() {
      if (this.$refs.providerForm.validate()) {
         this.signUp();
         this.$firestore.users.add({
            nome: this.nameProvider,
            telefone: this.telefoneProvider,
            email: this.emailProvider,
            endereco: this.enderecoProvider,
            numero: this.numeroProvider,
            cidade: this.cityProvider,
            distrito: this.distritoProvider,
            pais: this.paisProvider,
            complemento: this.complementoProvider,
            nomeContato: this.nomeContatoProvider,
            level: "2",
            uid: this.userId,
          });
      }
    },
  },
};

I am trying to pass the value of this.userId saved in the signUp() method to the createProvider() method for registration in Firestore.

Answer №1

Implement .bind(this) in your code to access this. in situations where direct access is not possible. Another option is to assign this to a variable and use that variable within the function.

signUp() {
      var selfVar = this;
       firebase.auth().createUserWithEmailAndPassword(this.emailProvider, this.passwordProvider)       
     .then((user) => {
     //  HERE I CREATE THE USER USING FIREBASE AUTH AND I'M TRYNG TO GET THE UID FROM THIS AND STORE IN THE this.userId
           
          selfVar.userId = user.user.uid;
          selfVar.authState(); // the method to 
        })
        .catch((error) => {
          console.log("ERRO", error);
        });
    }

Alternatively, consider using an async function directly to retrieve user information if the authentication call is successful

async signUp() 
{ 
    const user = await firebase.auth().createUserWithEmailAndPassword(this.emailProvider,this.passwordProvider); 
    if(user){
     console.log(user);
    } 
}

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 method for turning off client-side validation for a specific field with jQuery when a checkbox is selected?

This is the HTML code used in my MVC Razor page. <form> <input id="inputLPR" asp-for="LicensePlateNo" class="form-control"/> <input type="checkbox" id="isEnableBypass"><label for=&qu ...

Interacting with an iframe within the same domain

I'm currently working on an application in Angular 6 that requires communication with an iframe on the same origin. I'm exploring alternative methods to communicate with the iframe without relying on the global window object. Is there a more effi ...

Reorganize array of objects in JavaScript

So I am working with an array of objects structured like this: const data= [ { id: '6397f6f46b18bc89cb37053c', cost_center: null, plant: null, material: null }, { id: '6397f7166b18bc89cb372ff7', cost_center: &apo ...

Utilizing JavaScript to dynamically resize an element within a slide as soon as the slider transitions to the following slide

RESOLVED! ISSUE FIXED! While working on my personal website using WordPress and the Smart Slider 3 plugin, I encountered a problem with the positioning and size of an element in the second slide. Despite finding a tutorial explaining how to manually trigg ...

Implementing an OnChange Event for a Multi-Select Feature in a Vue.js Application

Here is the HTML code for my multi-select input: <select id="invitees_list1" class="form-select" multiple name="multi"> @foreach ($seatedTable->invitees as $invitee) <option> {{ $invitee ...

Performing API requests in NextJS using Prisma on a client-side page

Currently, I am faced with a challenge in fetching data from my database on a NextJS page designated as a client page using "use client" as required by the theme I am working with. At the moment, I have a page that fetches data from the database and redire ...

Setting up React Native on a Mac M1 device

I am currently setting up React Native on my MacBook M1 Despite having installed npm, JDK, Node, Rosetta, CocoaPod, VSCode, Android Studio, Xcode and more, when I try to run the command (npm start), the directories for iOS and Android are not present. The ...

Having trouble setting a JavaScript variable with a PHP session variable

In my PHP file, I have a session variable named $_SESSION['SESS_USER_TYPE'] set to a 2-character string. After the PHP script redirects to an HTML file, I need to retrieve this session variable in a JavaScript variable. This is how I am attempti ...

Engage with the item provided to an Angular2 component as an Input parameter

In a nutshell, the issue stems from a missing 'this' when referencing the @Input'ed variables. Currently, I have a parent class that will eventually showcase a list of "QuestionComponents". The pertinent section of the parent class templat ...

Generate and save a document

Upon clicking the button, I am trying to generate a CSV file and download it right away. My current approach is as follows: html: <a class="btn btn-primary" @click="downloadCsv">Download CSV</a> <a v-if="fileObjectUrl !== null" ref="down ...

techniques for accessing HTML source code through an AJAX call

I am trying to retrieve the HTML source of a specific URL using an AJAX call, Here is what I have so far: url: "http://google.com", type: "GET", dataType: "jsonp", context: document.doctype }).done(function ...

Sharing data between promises in Node.jsExplanation: In Node.js, passing values

Can someone assist with passing an object that I am creating step by step using promises with firebase? I would like to know if there is a more efficient way to construct the object without passing it through the promise chain. Below is the code snippet I ...

What is preventing my boolean from being altered?

Creating a basic calculator that can handle single-digit arithmetic. The current code is incomplete and redundant, so please avoid commenting on that. <!doctype html> <html> <head> <title>JavaScript Learning Zone</title> ...

Combine two redux actions and access the modified state in the second action

I'm facing a dilemma with a straightforward problem that I believe I have a solution for, but I'm uncertain about the effectiveness of my idea. Essentially, in the current state of things, I have an array property that requires updating just bef ...

Retrieving the caret's position in TinyMCE 4

Is there a way to retrieve the caret position in pixels (x & y dimensions) in TinyMCE 4 without obtaining row/column numbers? It should be relative to anything and achieved without adding any extra tags like bookmarks. Anyone know if TinyMCE has a method f ...

Utilize Photoshop's Javascript feature to extract every layer within the currently active document

Looking for insights on a Photoshop scripting issue. I have written a solution but it's not producing the correct result. Can anyone provide feedback on what might be wrong with the code? The goal is to retrieve all the layers in a document. Here is ...

Is there a reason why the integration of OnsenUI with Vue using vue-onsenui and v-ons-segment is not functioning

I am experiencing an issue with OnsenUI and VUE vue-onsenui v-ons-segment. Instead of displaying a button bar in a row as expected, I am seeing standard buttons. The problematic code resides in a customized Monaca CLI project utilizing the minimal VUE tem ...

Designing a Vue 3 JS component that showcases a collection of attributes for a movie catalog

I am aiming to utilize the movie_properties in order to store various details such as movie id, name, genre, comingSoon status, availability, thumbnail, and preview. It's important to note that I am working with an API call that contains all this inf ...

Unable to establish a breakpoint in a source-mapped file (illustrated using jQuery)

Having trouble setting a breakpoint on a minified JavaScript source file that is mapped to real sources using a source map file. An example of this problem can be seen on the website jquery.com. On this particular site, the imported script is jquery.min. ...

Tips for extracting parameters from a JSON String using JavaScript

When attempting to parse a JSON String, I am encountering an issue where the parsed value is coming up as undefined. You can view the code on this jsfiddle link. <input type="submit" onclick=testJSON() value="Test"/> <div i ...