简体   繁体   中英

How to get an authorized user in firebase v9 on javascript

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());
}
});

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());
  }
});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM