What is the best way to save the authResult object in Vue.js and FirebaseUI once authentication is complete?

I am working on implementing Twitter authentication using FirebaseUI in my Vue.js application.

Although I have successfully authenticated the user, I am struggling to figure out how to store information from the AuthResult object.

In my main component (App.vue), I have set up a listener for the onAuthStateChanged event to save the user details. This method works effectively, but I am unable to access the API credentials returned by Twitter within the user object.

firebase.auth().onAuthStateChanged((user) => {
  if (user) {
    this.user = user
    this.$router.push('/user')
  } else {
    this.$router.push('/login')
  }
})

The API credentials are included in the firebaseui.auth.AuthResult object, which is accessible in the FirebaseUI callback called signInSuccessWithAuthResult.

The issue I'm encountering is that I cannot invoke Vue.js functions from within this callback - I can't change data using this.foo, nor can I emit an event with this.$emit. I am only able to log the authResult object using console.log(), nothing more.

Q: How can I store the authResult object in my Vue application?

Here is a simplified version of my child Login component template:

<template>
   <div>
      <div id="firebaseui-auth-container"></div>
   </div>
</template>

<script>
import firebase from 'firebase'
import * as firebaseui from 'firebaseui'
export default {
  name: 'Login',
  data () {
    return {
      foo: ''
    }
  },
  mounted () {
    var uiConfig = {
      signInOptions: [
        firebase.auth.TwitterAuthProvider.PROVIDER_ID
      ],
      signInFlow: 'popup',
      callbacks: {
        signInSuccessWithAuthResult: function (authResult) {
          // this.$emit('updateAuthResult', authResult)
          // this.foo = 'bar'
          console.log(authResult)
          return true
        }
      }
    }
    var ui = new firebaseui.auth.AuthUI(firebase.auth())
    ui.start('#firebaseui-auth-container', uiConfig)
  }
}
</script>

Answer №1

Could the issue be related to the context we are in? You may want to refer to this discussion on When to Use vm. or this. in Vue.js

Have you tried the following approach:

mounted () {
    var vm = this
    var uiConfig = {
      signInOptions: [
        firebase.auth.TwitterAuthProvider.PROVIDER_ID
      ],
      signInFlow: 'popup',
      callbacks: {
        signInSuccessWithAuthResult: function (authResult) {
          vm.$emit('updateAuthResult', authResult)
          vm.foo = 'bar'
          console.log(authResult)
          return true
        }
      }
    }
    var ui = new firebaseui.auth.AuthUI(firebase.auth())
    ui.start('#firebaseui-auth-container', uiConfig)
  }

Answer №2

One potential solution to this issue could be utilizing an arrow function

mounted () {
 var configuration = {
  signInOptions: [
    firebase.auth.TwitterAuthProvider.PROVIDER_ID
  ],
  signInFlow: 'popup',
  callbacks: {
    signInSuccessWithAuthResult: (authResult) => {
      this.$emit('updateAuthData', authResult)
      console.log(authResult)
      return true
    }
  }
 }
 var configUI = new firebaseui.auth.AuthUI(firebase.auth())
 configUI.start('#firebase-auth-container', configuration)
}

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

Exploring the power of promise chaining within AWS Lambda

I'm feeling a bit confused about how Promise chaining works in AWS Lambda. exports.handler = async(event) => { firstMethod = () => { return new Promise(function(resolve, reject){ setTimeout(function() { ...

Is it recommended to use separate Controllers for each tab in Angular JS to load the pane?

Recently delving into the world of Angular JS and eagerly seeking expert advice and suggestions. Would it be advisable to use separate controllers for initializing each Tab to load the Pane content? Is assigning separate controllers a recommended approac ...

PUT Request Disallowed by Django Rest in Conjunction with Vue.js Frontend

I am attempting to send a PUT request to my RestAPI using Vue.js. It functions perfectly in my ModelViewSet view, but I am facing an issue of Method Not Allowed (PUT) when trying it through Vue.js. Interestingly, I can use "POST" within the same onSubmit f ...

Utilizing the WebSocket readyState to showcase the connection status on the application header

I am currently in the process of developing a chat widget with svelte. I aim to indicate whether the websocket is connected or not by utilizing the websocket.readyState property, which has the following values: 0- Connecting, 1- Open, 2- Closing, 3- Close ...

Is it possible to use both interfaces and string union types in TypeScript?

My goal is to create a method that accepts a key argument which can be either a string or an instance of the indexable type interface IValidationContextIndex. Here is the implementation: /** * Retrieves all values in the ValidationContext container. ...

"Enhancing user experience with JQuery and MVC4 through efficient multiple file uploads

Currently, I'm facing a challenge in uploading multiple files alongside regular form data. While I had successfully implemented this functionality in PHP before, I am now attempting to achieve the same in ASP.NET MVC4 using C#. Below is the HTML form ...

Getting content from a URL and storing it using Firebase Storage and Cloud Functions: a complete guide!

I have a real-time database where users can input the URL of an image. After triggering a cloud function upon creation/update, I am able to read the image's URL from the real-time database. Now, my goal is to download the image from the web (not uplo ...

javascript the debate between inline and traditional registration

Hey there, I'm a JavaScript beginner and currently learning about inline vs. traditional registration. I've managed to get code block 1 (inline) working perfectly fine, but unfortunately, code block 2 (traditional) isn't cooperating. Can som ...

VueJS added a new object to the array, but the data did not update reactively

Here is my current data layout days: [ { id: 0 name: 'Monday', times: [] }, { id: 1 name: 'Tuesday', times: [] } } I have implemented the following function to append an object to the times array. onT ...

Socket.io integration with JWT authentication

Having some trouble establishing a connection with JWT. It's not returning anything and I'm not very familiar with JWT so not sure where I might be going wrong. Unable to do anything on localhost:4000 due to the lack of connection. Any suggestio ...

Vue lifecycle hook - selectively halt component creation

Is it possible to stop the creation of a component during its lifecycle hook? For instance: beforeCreated() { // check value from vuex store if (this.$store.state.attendeesCount >= this.$store.state.maxAttendees) { // prevent further pr ...

Exploring the contrast of utilizing the `new Date()` function compared to Firestore's `new

I am developing a new app and need to calculate the time elapsed between the start and end of a run. When the run starts, I record a timestamp using the new Date() function in Firebase. (I opted for this over firestore fieldValue to avoid conflicts with o ...

Getting the value of a CSS Variable from Radix UI Colors with Javascript/Typescript: A step-by-step guide

Currently, I am attempting to dynamically retrieve the Radix Colors values in JavaScript. The reason for this requirement is that I generate these colors based on user input, resulting in values that are variable. As a result, I cannot hardcode the values. ...

JavaScript library for making HTTP requests

Can someone provide guidance on creating a JavaScript command line application that interacts with a public API using an HTTP client library? What is the preferred JavaScript HTTP library for this task? ...

What is the process for implementing text box validation on a button click within a gridview in asp.net utilizing javascript?

How can I implement textbox blank validation on button click within a gridview using JavaScript? My gridview has multiple rows with 2 textboxes and a save button in each row. I need to validate the textboxes when their corresponding save button is clicked. ...

In my development environment, the page does not have scroll functionality, but in the production environment, it is scrollable

Whenever I open a table or any other element with overflowing content, I encounter an issue with the scrolling bar. Even though the CSS includes overflow-y: scroll;, the scroll bar on the right remains in gray and does not allow me to scroll down when the ...

Is there a way to customize setInterval for a specific element?

For some time now, I've been working on creating a typing animation that triggers when links come into view during scrolling. However, I've encountered a problem with jQuery not selecting the correct element or the setInterval objects causing all ...

Exploring data visualization within a JSX Component

I am attempting to dynamically render a Card component that is mapped from an array of objects. However, I am encountering an "unexpected token error" and the URL is not rendering as expected. The goal is to display five cards based on the data within the ...

Utilizing an array for assigning values in conditional statements

I have been experimenting with toggling a CSS style on a couple of elements using an if statement. Currently, I have it working with several if statements, but I believe it can be simplified by utilizing an array with the values and just one if statement. ...

Setting up jsdoc on a computer with slow internet access can be a bit tricky, but with

Recently, I have been working on some JavaScript code and utilized the sublime jsdoc plugin for commenting. Now, my goal is to generate documentation from these comments. The challenge lies in the fact that I am developing this JavaScript on a machine loca ...