I have a file dedicated to handling Authentication functions for my React Native App. One of these functions getJWToken is an anonymous async function that tries to get the current user token by the following means:
const auth = db.auth()
// db === (Firebase.apps.length === 0 ? Firebase.initializeApp(config) : Firebase.app())
// the configuration of the Firebase DB occurs in a config file and db is exported.
const getJWToken = async () => {
auth.onAuthStateChanged(function(user) {
if (user) {
user.getIdToken()
.then(function(idToken) {
return idToken;
})
.catch(
(error) => {
console.log("Cannot get User Token: ", error);
}
)
}
});
}
Through console.log I'm able to see that the function returns the token as it's suppose to. The issues arrives when I'm using it in another async function in another file like so:
Service Folder index.js
import * as Auth from './AuthServices'
export {Auth}
App.tsx
// App.tsx
import {Auth} from './src/services'
// The rest in inside an Async Function
signOut: async () => {
let token
token = await Auth.getJWToken()
console.log("token: ", token) // results in undefined
}
Token results in undefined. I have no means of returning the token value from the promise function. I've tried using return on auth.onAuthStateChanged but that results in token evaluating to [Function Bound]. await on auth.onAuthStateChanged does nothing either. I'm truly stumped.
onIdTokenChangedinstead ofonAuthStateChangedif you're grabbing the idToken. (2) These trigger every time there's a change—a promise can only resolve a value once. You should be listening for this event and storing the result somewhere. Then,getJWToken()can fetch wherever you've cached the token.