[Vuejs]-How can i get the user in firebase database, to write from a component with vuejs?

0👍

You’ll have to save the uid upon login, so you can use it later.

The best way to handle that would be using Vuex, but, without better knowledge of your app, the simplest way is just to create a uid property in the data of your root component, like.

// probably main.js file
new Vue({
  el: "#app",
  data: {uid: null}, // added this
  components: { App },
  template: "<App/>"
});

Then it will be globally available as:

this.$root.uid

And you can update it as:

this.$root.uid = 'newUserId';

Having it that way, you can consider that, if $root.uid is set, then the user is logged in.

So, to set it, change your login method:

methods: {
login: function(e) {
  firebase
    .auth()
    .signInWithEmailAndPassword(this.email, this.password)
    .then(
      user => {
        alert(`You are logged in as ${user.email}`);
        this.$root.uid = user.uid;                       // added this
        this.$router.go({ path: this.$router.path });
      },
      err => {
        alert(err.message);
      }
    );
  e.preventDefault();
 }
}

Then turn contenidoFormulario into a function like:

export const contenidoFormulario = (uid) => db.ref('formularioContenido/' + uid);

And, when using it inside a component, do:

 methods: {
  enviarMensaje(){
   contenidoFormulario(this.$root.uid).set({        // changed here
      mensaje: this.mensaje,
      boton1: this.boton1,
      usuario: this.usuario,
   })
  }
 }

That should work.

Note: don’t forget to put somewhere in your code this.$root.uid = null; for logout.

Note[2]: Since you are using Firebase, I recommend you take a look in vuefire. It makes the integration much easier.

Leave a comment