Having trouble getting the accessToken from the user object in Firebase + Typescript?

I'm facing an issue in my MobX store where I can't retrieve the accessToken from Firebase login, even though the data is present. This pertains to a React-Native environment.

Example:

class GlobalStore {

    @observable loggedIn: boolean;

    @observable user: any;

    @action firebaseStatup = () => {

        firebase.initializeApp({
            apiKey: "somestring",
            authDomain: "app.firebaseapp.com",
            databaseURL: "https://app.firebaseio.com",
            projectId: "app",
            storageBucket: "app.appspot.com",
            messagingSenderId: "1234
         });
         firebase.auth().onAuthStateChanged((user) => {
             this.loggedIn = !!user;
             if (user) {
                  this.user = firebase.auth().currentUser;
                  console.log(this.user); // Displays an Object containing stsTokenManager.accessToken which is the JWT?
                  console.log(this.user.stsTokenManager.accessToken)
              }
          })
     };

console.log(this.user); shows a detailed user object with all information. However, trying to access stsTokenManager.accessToken directly throws an error:

undefined is not an object (evaluating '_this.user.stsTokenManager.accessToken')

How can I successfully retrieve the accessToken that is clearly available?

Answer №1

The main issue arose with the fact that the variable user was returning a promise instead of the expected value. To address this, I found a solution that involved storing it in AsyncStorage:

// ... Working with Firebase

    firebase.auth().onAuthStateChanged((user) => {
        this.loggedIn = !!user;
        if (user) {
            this.user = firebase.auth().currentUser;
            user.getIdToken()
                .then(token => this.saveTokenToStorage(token))

        }
    });

@action async saveTokenToStorage(token: string) {
    try {
        await AsyncStorage.setItem('authentication', token);
    } catch (error) {
        // An error occurred while trying to save the data
    }
};

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 process of creating a new array by grouping data from an existing array based on their respective IDs?

Here is the initial array object that I have: const data = [ { "order_id":"ORDCUTHIUJ", "branch_code":"MVPA", "total_amt":199500, "product_details":[ { ...

The Firebase/Firestore security rule seems to be malfunctioning in my case

I am currently developing a compact PWA app/game built in Ionic/Angular with Firestore backend. I have decided not to use Google authentication, instead allowing users to create their own username and password. In my Firestore database, I have a 'user ...

What is the proper way to define the properties for a higher-order component that will encompass the Route component from React Router?

I am currently working on a PrivateRoute component that will wrap the Route element from react-router-dom. My goal is to verify if the user has a token and then decide whether to allow or deny access to the destination screen. However, I'm encounterin ...

The object returned by bodyParser is not a string but a data structure

I have been working on implementing a JSON content listener in Typescript using Express and Body-parser. Everything is functioning perfectly, except when I receive the JSON webhook, it is logged as an object instead of a string. import express from 'e ...

Is there an alternative method to invoke the function aside from setTimeOut()?

if(i==1){ this.resetScreens(); this.editJobScreen1 = true; if(this.selectedLocations.length > 0){ this.locationService.getLocationByInput({ maxResultCount:16, skipCount: 0 }).subscribe((ele)=>{ ...

Observing network events with Ionic 2, RxJS5, and the Cordova network plugin

Is it possible to create an RxJS observable using the fromEvent method based on the Cordova network connection plugin? I am attempting this with Ionic 2. I have noticed that the Cordova network connection plugin offers two events (online/offline). How ca ...

Webpack 2.7.0 throws an error: "Unexpected parameter: theme"

At the moment, I am on webpack 1.16.0 and using --theme as an argument to set the output path and plugin paths. The command appears as: rimraf dist && webpack --bail --progress --profile --theme=<name of theme> However, as I try to upgrade ...

Is there a way for me to trace the source of an unclear typescript error message about redeclaring a block-scoped variable named 'length'?

After deleting my node modules and running yarn, I encountered a new error that stated: node_modules/typescript/lib/lib.dom.d.ts:17687:13 - error TS2451: Cannot redeclare block-scoped variable 'length'. 17687 declare var length: number; Despite ...

Troubleshooting the clonewithrows array problem in react-native

I am currently facing an issue while trying to populate a Listview in my react-native application using data from Firebase. The error message I am receiving is as follows: "Objects are not valid as a React child (found object with keys {title}). If you me ...

Unlocking the Secrets of AnimatedInterpolation Values

I have a question about how to access the value of an AnimatedInterpolation in react-native without resorting to calling private code. To achieve this, I first create an animated value and then wrap it in an interpolation like so: animated = new Anima ...

Creating a checkbox list in Angular tied to ngModel and additional attributes sourced from a JSON array

I am currently developing an application using Angular. I have created a checkbox list where each checkbox has a specific ngModel value assigned to it. To achieve this, I have defined a JSON object in my TypeScript component file which looks like this : ...

Loop through object properties with *ngFor

Seeking suggestions on how to iterate over object keys in HTML using *ngFor within Angular 12. The provided data structure is as follows: { "data": [ { "student1": { "name": "Jhon", &quo ...

When multiple tabs of a Chrome extension are opened, the onMessage.addListener in the service worker is triggered twice for each tab

Whenever I have two or more of my extension tabs open, the functions chrome.runtime.sendMessage and chrome.runtime.onMessage.addListener seem to run twice. However, when I only have one tab open, everything works fine. What could be causing this issue and ...

What is preventing me from including an additional parameter in a function in TypeScript?

I am currently developing a task management application. I am facing an issue while attempting to incorporate the event and items.id into a button function for actions like delete, edit, or mark as completed. While this functionality works smoothly in pla ...

Is it possible to create a data structure that enforces specific keys and values types during initialization?

When styling react components with MaterialUI's sx property, I've found that keeping the full style definition inline can lead to cluttered and overwhelming component bodies. To combat this, I've moved all the style definitions into a consta ...

The error message "Property 'getPickerData' is not found on type 'RefObject>'" indicates that the function getPickerData is not available on

Struggling to incorporate this custom picker from React Native Phone Input repository into a TypeScript project. Being new to react native, I'm not sure if I set up my ref correctly, but here's what I have so far. import * as React from 're ...

What is the correct way to enhance a generic interface by adding a new generic parameter using declaration merging in TypeScript?

I currently have a simple express application that provides token-based authentication and utilizes Zod for creating schemas to validate incoming data. Specifically, I have defined two schemas: CreateUserSchema {firstname, lastname, email, pass, passConf ...

Building a versatile setting within a child component by incorporating TypeScript and deriving state data from the parent component

In my page component, I have set a state called formData. Now, I want to create a context within my form component so that I can utilize it in each child form component. Everything works smoothly without TypeScript. However, when using TypeScript, I encoun ...

Error TS2307: Module 'angular' could not be located

I have encountered an error in my project and despite searching for solutions, I haven't been able to find one that addresses my specific issue. It seems like a simple problem, but I can't figure out what I'm missing. The error arises in th ...

Exploring ways to retrieve checkbox values instead of boolean values upon submission in Angular

I am currently working with a template-driven form and facing an issue. Despite receiving true or false values, I actually need to retrieve the value of checkboxes. <form #f = "ngForm" (ngSubmit) = "onClickSubmit(f.value)"> ...