I have an observer who checks whether the user has logged in, if SO, writes it to the AuthUser variable.
But the variable lives only in the observer
export let authUser = "";
const user = auth.currentUser;
function WatchToUser() {
onAuthStateChanged(auth, (user) => {
if (user) {
authUser = user.email;
} else {
}
});
Later I want to check this user on another page, if he is authorized, then show him the database, if not, then send it to the home page. But on another page, the variable is already an empty string.
It turns out that when switching to another html page, the user disappears, what to do?
showUsers.addEventListener("click", () => {
if (authUser != null && authUser != "") {
window.location.replace("users.html");
} else {
modalVisible("Need to login", isError());
}
});
CodePudding user response:
You can create a function that returns a Promise
once Auth state is loaded like this:
function getUser() {
return new Promise((resolve, _) => {
const unsub = onAuthStateChanged(auth, (user) => {
unsub();
return resolve(user) // or throw error is user is not logged in
})
})
}
// await getUser()
However, it seems you are calling a function when a button is click. So the auth state could be loaded already so you could just use currentUser
(assuming the page is shown to user only if they are authenticated).
showUsers.addEventListener("click", () => {
const user = auth.currentUser;
if (user) {
window.location.replace("users.html");
} else {
modalVisible("Need to login", isError());
}
});