[英]Firebase keep track if is user authenticated
我試圖弄清楚無論用戶是否登錄,如何保持我的應用程序的全局 state 。 Do I have to have only one onAuthStateChanged()
in my JavaScript file to keep track of state changed and add all HTML elements there like account details or is it a good idea to add multiple onAuthStateChanged()
in each HTML file and have something like
auth.onAuthStateChanged(function (user) {
if (user) {
document.getElementById("user-header-username").textContent = `Hi ${user.displayName}`;
} else {
document.getElementById("user-header-username").textContent = "Sign in";
}
}
我很困惑,無法弄清楚如何以如此有效的方式構建我的應用程序,以在用戶登錄時顯示特定部分,如果用戶未登錄則顯示其他內容,以及如何使其在整個應用程序中持久存在。 如果有人能解釋這個過程是如何工作的,以便了解如何進行,我將不勝感激。 我正在為該項目使用香草 JavaScript。
您需要某種應用程序 state。
我建議你 redux: https://redux.js.org/
使用 Redux 您的代碼將如下所示(偽代碼):
auth.onAuthStateChanged(function (user) {
if (user) {
store.dispatch("user-logged-in", user)
} else {
store.dispatch("user-logged-out")
}
}
store.subscribe("user-logged-in", (user) => {
document.getElementById("user-header-username").textContent = `Hi ${user.displayName}`;
// other side effects
})
store.subscribe("user-logged-out", () => {
document.getElementById("user-header-username").textContent = "Sign in";
// other side effects
})
Do I have to have only one onAuthStateChanged() in my JavaScript file to keep track of state changed and add all HTML elements there like account details or is it a good idea to add multiple onAuthStateChanged() in each HTML
每個加載的頁面至少需要一個 auth state 觀察者,以便每個頁面能夠訪問當前用戶。 這很正常。
如果您出於某種原因每頁需要多個觀察者,那也沒關系。 由您決定哪些代碼最能滿足您的應用程序的需求。
觀察者的主要目的是在已知用戶登錄時通知您(這不會在頁面加載時立即發生)。 它還會告訴您用戶是否已注銷。 您如何處理這些事件取決於您自己。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.