Is there a way to have the user input data into a Firebase database directly from a Vue.js component?

Any assistance for a beginner like me would be greatly appreciated. I am currently working with vuejs and firebase to write data into the database from a vue component. I have successfully implemented authentication and writing functionality, but now I want each user to write in their own component rather than all users on the same component. Below is my code:

Users log in to this component (login.vue):

<template>
<div>

<h2> auth </h2>

   <div class="container">
   <div class="row">
     <div class="col s12 m8 offset-m2">
       <div class="login card-panel green white-text center">
         <h3>Login</h3>
         <form action="index.html">
           <div class="input-field">
             <i class="material-icons prefix">email</i>
             <input type="email" id="email" v-model="email">
             <label class="white-text" for="email">Email Address</label>
           </div>
           <div class="input-field">
             <i class="material-icons prefix">lock</i>
             <input type="password" id="password" v-model="password">
             <label class="white-text" for="password">Password</label>
           </div>
           <button v-on:click="login" class="btn btn-large btn-extended 
            grey lighten-4 black-text">Login</button>
         </form>
       </div>
     </div>
   </div>
   </div>
  </div>
</template>

<script>
import firebase from 'firebase';
export default {
name: 'login',
data: function() {
 return {
  email: '',
  password: ''
 };
},
methods: {
login: function(e) {
  firebase
    .auth()
    .signInWithEmailAndPassword(this.email, this.password)
    .then(
      user => {
        alert(`You are logged in as ${user.email}`);
        this.$router.go({ path: this.$router.path });
      },
      err => {
        alert(err.message);
      }
    );
  e.preventDefault();
 }
}
};
</script>

In this component(envio.vue), users can write and send data to Firebase:

<template>
 <div id="app">
  <form @submit.prevent="enviarMensaje">
      <textarea v-model="boton1" cols="30" rows="1"></textarea>
      <br>
      <textarea v-model="mensaje" cols="30" rows="10"></textarea>
      <br>
      <input type="submit" value="Enviar mensaje">
  </form>
  <hr>
  <h1>texto con idicaciones</h1>
 </div>
</template>


<script>
import firebase from 'firebase'
import { contenidoFormulario } from '../firebase'

 export default {
  data: function() {
  return {
  mensaje: null,
  boton1: null,
  usuario: '',
  }
 },

 methods: {
  enviarMensaje(){
   contenidoFormulario(uid).set({
      mensaje: this.mensaje,
      boton1: this.boton1,
      usuario: this.usuario,
   })
  }
 }
}
</script>

Below is the structure of the Firebase database in JSON format:

Project

-- formularioContenido:

     boton1: "..."

     mensaje: "..."

     usuario: "..."

This is the desired structure:

Project

-- formularioContenido:

     --user A

          boton1: "..."

          mensaje: "..."

          usuario: "..."

     --user B

          boton1: "..."

          mensaje: "..."

          usuario: "..."

The code for '../firebase':

import { initializeApp } from 'firebase';



const app = initializeApp({
    apiKey: """",
    authDomain: """
    databaseURL: "",
    projectId: "",
    storageBucket: ""
    messagingSenderId: ""
});


export const db = app.database();
export const contenidoFormulario = db.ref('formularioContenido');

Main.js file:

let app;
firebase.auth().onAuthStateChanged(user => {
  if (!app) {

   app = new Vue({
   el: '#app',
   data: {uid: null}, 
   router,
   template: '<App/>',
   components: { App }
 });

} });

Logout functionality:

<template>
<div id="app">
<section>

   //...

  <li v-if="isLoggedIn"><button v-on:click="logout" class="btn 
   black">Logout</button></li>

</section>
</div>
</template>

<script>
import firebase from 'firebase';
export default {
  name: 'navbar',
  data() {
   return {
    isLoggedIn: false,
    currentUser: false,
  };
 },
  created() {
    if (firebase.auth().currentUser) {
     this.isLoggedIn = true;
     this.currentUser = firebase.auth().currentUser.email;
  }
 },
  methods: {
   logout: function() {
     firebase
     .auth()
     .signOut()
     .then(() => {
      this.$root.uid = null;  
      this.$router.go({ path: this.$router.path });
     });
    }
   }
  };

  </script>

Answer №1

Make sure to remember the uid when the user logs in, so you can access it later.

The most efficient way to manage this is by using Vuex. However, if you're looking for a simpler solution without much knowledge of your app, you can just create a uid property in the root component's data, like this:

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

This will make it accessible globally as:

this.$root.uid

You can update it with:

this.$root.uid = 'newUserId';

By having it set up this way, you can consider that the user is logged in if $root.uid has a value.

To implement this, adjust your login method as follows:

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();
 }
}

Convert contenidoFormulario into a function like this:

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

When using it within a component, do the following:

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

This setup should work correctly.


Note: Remember to include somewhere in your code this.$root.uid = null; for a proper logout functionality.

Note[2]: Considering you are using Firebase, I suggest checking out vuefire. It simplifies the integration process.

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

JQuery is not able to render Hindi content properly

I am attempting to showcase some Hindi words using JQuery because these are essential contents that need to be displayed on every page of the website. Please note that this is a static website built with HTML and JQuery/JavaScript. Below is my JS file: in ...

One effective way to redirect after a PUT request and display a one-time message

Here's what I'm aiming for in terms of desired behaviour: A user navigates to a password change web page. The user completes the form and it is sent via PUT request to our REST server. Upon successful completion, the user is redirected to their ...

Using Node.js and Express for redirecting to a custom URL

Having an issue with redirection on my small nodejs/express app. The goal is to redirect to an external URL with input values from a form after submitting. index.html <form method="POST" action="https://192.0.2.1/abc.html"> <input name="name ...

How can I remove the back button that the Ionic framework adds when using $state.go('app.home') to navigate to a page?

I have an app with a sidebar menu. Currently, I am on the second page and I am calling a controller function that redirects me to the first page using: $state.go('app.home'); The issue I am facing is that on this page, a back button is displayed ...

Mobile Devices Experiencing Issues with Proper Resizing of Three.JS Panorama

I'm currently working on a project using Three.Js and its device orientation library to create a panorama that users can navigate by moving their phones. Initially, everything looks great as intended: Proper Panorama However, upon refreshing the pag ...

AutoComplete feature activates when I choose a suggestion from the dropdown menu

<Autocomplete disablePortal id="geo-select-country" options={all_country} defaultValue={nation} onChange={(event, selected_nation) => { set_nation(selected_nation); }} ...

Strange glitches and slow loading problems plaguing website. (GoDaddy)

TackEmporium.com Lately, I have been revamping my website, which was originally given to me by a friend. I have been making slight adjustments to update its appearance while keeping its classic look with enhanced resolution and cleaned-up HTML5 code. Rec ...

Manipulating cursor position in React's contentEditable

I created a simple component class ContentEditable extends React.Component { constructor(props) { super(props); this.handleInput = this.handleInput.bind(this); } handleInput(event) { let html = event.target.innerHTML; if (this.props. ...

Implementing Jquery to Identify the Matching Indices of Two Arrays

I need to find the indices of similar values in array1 and array2, and then save them in a variable named stored_index. array1 = ["50","51","52","53","54","55","56","57","58","59"]; array2 = ["59","55","51"]; The desired result for stored_index is: sto ...

Encountering an issue with finding the module `scheduler/tracing` in React Native

Encountering an error during the react-native run-android process: Error: Unable to resolve module `scheduler/tracing` from `/Users/miftahali/projects/react/appscustomec/node_modules/react-native/Libraries/Renderer/oss/ReactNativeRenderer-dev.js`: Module ...

Guide on how to fill a jQuery DataTable with data from an XMLHttpRequest response

I have come across multiple inquiries on this topic, but none of the solutions provided have brought me close enough to resolving my issue. Hopefully, someone out there will find it simple to address. I am attempting to populate a DataTable using an XHR re ...

Updating the parent controller's scope from a directive in AngularJS does not reflect changes

HTML: <div ng-app="myApp" ng-controller="Controller"> <test ng-if="toggle" props="condition"></test> </div> Javascript: var myApp = angular.module('myApp', []); myApp.controller('Controller', ['$scop ...

React Native: LogBox now including all warnings

Looking for a way to use LogBox to filter out specific log messages, but despite my attempts to ignore them, they still show up in the console... "react-native": "0.68.2", In my main file (index.js), this is how I've tried to impl ...

Adding a stylesheet dynamically in Angular 2: A step-by-step guide

Is there a method to dynamically add a stylesheet URL or <style></style> in Angular2? For instance, if the variable isModalOpened is set to true, I want to apply certain CSS styles to elements outside of my root component, such as the body or ...

Thirteen consecutive attempts to fetch information have resulted in failure

I've encountered an issue while attempting to fetch data from my .NET Core 7 API. The error message I'm receiving is as follows: *Unhandled Runtime Error Error: fetch failed Call Stack Object.fetch node:internal/deps/undici/undici (11413:11) pro ...

What is the best way to add new input fields dynamically using the push() function in AngularJS?

I'm currently working on implementing an add more field feature in angularjs. Here is the code that I am using: Javascript <script> function FruitsController($scope){ var div = 'Apple'; $scope.fruits= ...

How can I send data to components that are dynamically added?

Recently, I put together a test on a codepen that allows me to dynamically add components to an existing page. However, the challenge lies in passing props to these components. While browsing through another question, I found someone else struggling with a ...

Could an average user potentially access a hidden button meant only for management by examining a website and discovering how to activate it?

Create a website catering to both regular users and management. For instance, normal users are identified as 1, so if their account ID is also 1, they can access a page with limited functionality. Similarly, management is identified as 2, and they too acce ...

Validation of Regular Expressions in Javascript

I am trying to implement control validation using Javascript. The validation criteria states that the number should consist of a maximum of 12 digits, with the first 7 being '9900000' followed by either a '0' or a '1', and en ...

The Array map function is not displaying the list within a React component that is based on a Class

I am having trouble displaying a list of food items in my Parent component FoodBox.js and its child component FoodItems.js. I am using the map() method, but the <ul> element is showing up empty. Here is my code for FoodBox.js const FOOD_ITEMS = [ { ...