Reputation: 105
I've been trying to make a util method which will return either the user object or if the user object exists. With no params it should return a boolean and with the param "getUser" it should return the user object, but it is always returning undefined. This seemed to work for a while, but then I took a break and came back and it was always returning undefined. Code below
import { getAuth, onAuthStateChanged } from "firebase/auth";
export default function checkAuthState(type?:string){
const auth = getAuth()
onAuthStateChanged(auth, (user) => {
if (user) {
if(!type) return true
if(type === "getUser") return user
else return true
} else {
if(!type) return false
else return false
}
});
}
Upvotes: 0
Views: 1092
Reputation: 599601
Your return true
returns a value to onAuthStateChanged
, which is what calls your callback. The onAuthStateChanged
is not doing anything with that value.
If you want to have a promise that resolves once the initial user state has been restored, you can do that with:
function checkAuthState(type?:string){
const auth = getAuth()
return new Promise((resolve, reject) => {
const unsubscribe = onAuthStateChanged(auth, (user) => {
if (user) {
if(!type) resolve(true)
if(type === "getUser") resolve(user)
else resolve(true)
} else {
if(!type) resolve(false) false
else resolve(false)
}
unsubscribe();
});
})
}
And then call it like this:
checkAuthState().then((result) => {
console.log(result);
})
Or when using async
/await
:
const result = await checkAuthState();
console.log(result);
Upvotes: 5