Information on Vue.js and Firebase User Data

I am currently working on an application that integrates Vue.js and Firebase.

So far, I have successfully implemented the login functionality using email/password and can store the user information from firebase.auth() in the state.currentUser of Vue.js.

However, according to Firebase guidelines, there is more data stored under '/users' reference. For example, /users/uid

I would like to also retrieve this data into the vuex store (state.userMeta) so that I can utilize it throughout the site. The issue is that it does not work after a refresh. If I do not refresh, logout and then log back in, it populates the state correctly.

Your assistance with this matter would be greatly appreciated!

James

auth.js

import { auth, db } from '@/config/database'
import store from '@/vuex/store'

const init = function init () {
  auth.onAuthStateChanged((user) => {
    if (user) {
      store.dispatch('setUser', user)
    } else {
      // User is signed out.
      store.dispatch('setUser', null)
    }
  }, (error) => {
    console.log(error)
  })
}

export { init }

store.js

import Vue from 'vue'
import Vuex from 'vuex'
import createPersistedState from 'vuex-persistedstate'
import { db } from '@/config/database'

Vue.use(Vuex)

const state = {
  currentUser: null,
  userMeta: null
}

const mutations = {
  SET_USER (state, user) {
    if (user) {
      state.currentUser = user
      db.ref('users/' + user.uid).on('value', function (s) {
        state.userMeta = s.val()
      })
    } else {
      state.currentUser = null
      state.userMeta = null
    }
  }
}

const actions = {
  setUser ({commit}, user) {
    commit('SET_USER', user)
  }
}

const getters = {
  currentUser: state => state.currentUser
}

export default new Vuex.Store({
  state,
  mutations,
  actions,
  getters,
  plugins: [createPersistedState()]
})

App.vue

<template>
  <div id="app">
    <router-view></router-view>
  </div>
</template>

<script>
import * as auth from '@/config/auth'

const initApp = function initApp () {
  auth.init()
}

export default {
  name: 'app',
  created: initApp
}
</script>

<style lang="scss" src="./assets/sass/style.scss"></style>

main.js

// The Vue build version to load with the `import` command
// (runtime-only or standalone) has been set in webpack.base.conf with an alias.
import Vue from 'vue'
import App from './App'
import VueFire from 'vuefire'
import router from './router'

Vue.config.productionTip = false
Vue.use(VueFire)

import store from '@/vuex/store'

/* eslint-disable no-new */
new Vue({
  el: '#app',
  router,
  store,
  template: '<App/>',
  components: { App }
})

Answer №1

Refreshing the page clears Vuex state.

To address this issue, I followed these steps:

In main.js

new Vue({
el: '#app',
router,
store,
created() {
    Firebase.auth().onAuthStateChanged((user) => {
            if (user) {
                this.$store.state.user = this.$firebase.auth().currentUser
            } else {
                this.$store.state.user = null
            }
        })
    },
render: h => h(App)
})

This ensures that your state is synchronized automatically upon refreshing the page.

In your components

computed: {
    user() {
        return this.$store.state.user
    }
},

Attempting to access

this.$firebase.auth().currentUser
after a refresh won't work - but resetting the state through Auth changes solves the problem.

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

Establish a connection to couchDB using JavaScript on the server side

I'm working on a piece of code that involves using Restify to set up a server in node.js and create specific routes. My goal is to interact with CouchDB by performing actions such as GET, POST, DELETE, and PUT. var restify = require("restify"); var s ...

When the user clicks on a checkbox, jQuery should have the ability to retrieve the data from a table with 9000 rows

I am in need of a straightforward example that demonstrates how jQuery can fetch the contents of a table with more than 9000 rows. When the user clicks on the checkbox next to a table row, the checked rows should be displayed on the same view page. Can you ...

Ensure that JavaScript is compiled once the HTML has finished loading

I am trying to execute some JavaScript code after the HTML content has been loaded. var gifApp = angular.module('gifApp', []); function MainCtrl ($scope) { $scope.push = function() { $("body").html("<div>{{ 1 + 1 }}</div>") ...

Discovering the process to retrieve an uploaded image with vue.js

Help needed with a code snippet for multi-upload images in Vue.js. The functionality issue I am facing is that when uploading an image, only the image name appears in the console terminal instead of the actual image. I want to save the image in the backend ...

Transmit information using JSON format in Angular 8 using FormData

i am struggling with sending data to the server in a specific format: { "name":"kianoush", "userName":"kia9372", "email":"<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="bcd7d5ddd8ce85...@example.com</a>" } H ...

Issue with Nuxt.js social media preview: 404 error when sharing on Facebook or Twitter

I am currently using Nuxt.js to build my website and I want to share the pages on social media platforms like Facebook, Twitter, and WhatsApp. I have added the necessary opengraph meta tags to the pages, but when I try to share them on social networks, the ...

Exploring Angular.js: Finding the correct path in a JSON array

Within my Angular application, I have a $scope variable defined as follows. $scope.roleList2 = [ { "roleName" : "User", "roleId" : "role1", "children" : [ { "roleName" : "subUser1", "roleId" : "role11", "collapsed" : true, "children" : [ ...

Retrieving the value of the selected radio button

How do I access the value of a clicked radio button? I am trying to create a custom filter based on the gender selected in my <form>. However, when using the filter and orderBy in my ng-repeat, it is not functioning correctly. You can view an examp ...

Creating curved arcs within a polyline by utilizing the bulge feature in THREE.JS

Currently, I am importing a CAD file from a DXF format and I am looking for a way to draw an arc between two arbitrary points with a bulge value. My approach involves using THREE.Line to create segments of the arc. This resource outlines some of the essen ...

Guide to retrieving table data using jQuery in a Vue.js function

I have a simple table set up in my Laravel blade file. When the edit button is clicked, it triggers a Vue method. <types-page inline-template> <div> <!-- table --> <table id="choose-address-tab ...

Having trouble with jQuery div height expansion not functioning properly?

Having a bit of trouble with my jQuery. Trying to make a div element expand in height but can't seem to get it right. Here's the script I'm using: <script> $('.button').click(function(){ $('#footer_container').anim ...

The search button is malfunctioning after I submit search data and generate dynamic HTML using axios

When a user clicks on the search button, I retrieve the input value and then use axios to send a GET request with the search data. Everything works fine, but when I query the database and dynamically create data from the mongoose data, the page reloads w ...

Optimizing row display for each page with Material UI's pagination feature

I've been attempting to utilize Material UI table pagination to show 5 rows per page, but for some reason it displays all items on the page and doesn't switch between pages. I'm having trouble figuring out where I'm going wrong. To help ...

Can JavaScript be used to determine if any code has been executed from the browser's console?

I'm currently developing a JavaScript game and I want to prevent cheating. Is there a way for me to track and record commands entered in the JavaScript console? Here's a basic outline of what I have in mind: consoleCommands = ""; window.console ...

Managing comments in Vue HTML

Currently utilizing Vue for generating an html template and facing the need to incorporate html conditional comments within the code snippet below. var productTemplate = new Vue({ el: '#myApp' }); <script src="https://unpkg.com/<a hr ...

The functionality of JQuery .change() is limited to one occurrence

Here is my JavaScript code snippet: jQuery(document).ready(function(){ const select = $('...'); //select element const input = $('...'); //input element select.change(doSomething()); input.change(doSomething()); f ...

The Mongoose model fails to include any additional value upon its return

Currently, I am attempting to execute two queries and merge the results before sending them back to the client. Here is an example of my middleware: exports.shipmentByID = function(req, res, next, id) { Shipment.findById(id) .populate('u ...

Is there a way to seamlessly transition between images in a slider every 3 seconds using javascript?

<!DOCTYPE html> <html> <head> <title>Hello</title> <meta http-equiv="Content-Type" type="text/html" charset="UTF-8"/> <style> *{margin:0; padding:0;} .mySlides{ position:relative; width:1000px; ...

What is the best way to use the axios API query parameters?

I recently came across an API with a unique structure in the params key, resembling an array but not quite. I'm curious how it is implemented in axios. {baseUrl}/list?filter[v3_p.name]=Package Data&filter[pro.name]=Indosat&filter[pp.category] ...

Utilize Javascript to convert centimeters into inches

Can anyone help me with a JavaScript function that accurately converts CM to IN? I've been using the code below: function toFeet(n) { var realFeet = ((n*0.393700) / 12); var feet = Math.floor(realFeet); var inches = Math.round(10*((realFeet ...