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.
You have to return at two more places as show in the code . Please reply with this modification, ket us c
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 () => {
return auth.onAuthStateChanged(function(user) {
if (user) {
return user.getIdToken()
.then(function(idToken) {
return idToken;
})
.catch(
(error) => {
console.log("Cannot get User Token: ", error);
}
)
}
});
}
While I no longer use this code snippet I was able to solve it like so:
getJWToken
export const getJWToken = async () => {
let result;
// await is needed here
await auth.onAuthStateChanged(function(user) {
if (user) {
console.log("user")
// save this promise to result
result = user.getIdToken()
.then(function(idToken) {
return idToken;
})
.catch(
(error) => {
console.log("Cannot get User Token: ", error);
}
)
}
});
// return the user.getToken() promise
return result