I am using one line arrow functions a lot, if they are well written I believe they can make code easier to read. I believe that the following code can be easily transformed into one liner but I can't figure out how. Any ideas please? I am asking more just from curiosity.
const getUID = async () => {
let uid;
await firebase.auth().onAuthStateChanged(async (user) => {
if (!user) await firebase.auth().signInAnonymously();
uid = user.uid;
});
return uid;
};
1 Answer 1
First of all, onAuthStateChanged
expects a callback and can be fired multiple times. To resolve that you can use unsubscribe()
after the first success.
Secondly, for your code to work, you need to wait for signInAnonymously
. At the moment you assign it to a temporary variable, but I can't see it working. Because onAuthStateChanged
accepts a callback that can be fired multiple times, it won't wait in the main scope. To solve this, I suggest using Promise constructor.
Finally, you call signInAnonymously
, but you don't do anything with its response. You need to use user.uid
if the user is logged in, otherwise you need to use signInAnonymously().user.uid
So the final solution:
const getUID = async () => new Promise(resolve => {
const unsubscribe = firebase.auth().onAuthStateChanged(user => {
unsubscribe();
resolve(user ? user.uid : firebase.auth().signInAnonymously().then(v => v.user.uid))
});
})
const uid = await getUID()
Explanation:
- Wrap everything to Promise and resolve it when we get
uid
- Auth & listen on
onAuthStateChanged
- Unsubscribe on the first
onAuthStateChanged
callback trigger (because one trigger it's enough in your case) - Check if a user is defined (that means the user is signed in), resolve promise with user
uid
- If the user is not defined, use
signInAnonymously
to sign anonymous user, resolve that user `uid.
onAuthStateChanged
expects a callback and is supposed to be used as an observable that can fire multiple times, but you're trying to use it as a promise, waiting for the first change only. You would need to immediately unsubscribe, similar to this code. Also you should not pass anasync
function as a callback. \$\endgroup\$onAuthStateChanged
is not one time job. Thanks for explaining! \$\endgroup\$