[英]Firebase keep user logged in when navigating to other pages
我目前能夠登錄我的用戶帳戶並在仍然登錄的情況下成功導航到我的儀表板,但是當我 go 到任何其他頁面時,我的登錄狀態消失了。 另一個問題是在更新我的用戶信息時,我如何編寫 function 以便它根據誰登錄來更新信息? 我在下面提供了我的代碼。 謝謝!
編輯個人資料 JS:
// Initialize Firebase
firebase.initializeApp(firebaseConfig);
// Initialize variables
const auth = firebase.auth()
auth.onAuthStateChanged( auth,user => {
var user = firebase.auth().currentUser;
if (user) {
alert("User active: ");
// User is signed in.
var email = user.email;
var uid = user.uid;
//Take user to a different or home page
window.location.href ="editprofile.html?id=" + uid;
} else {
alert("No active user please signup or sign in.");
window.location.href ="login.html?error";
}
});
var studioName, email, password, firstName, lastName, address, country, state, city, zip, phoneNumber;
function updateStu() {
//Get data
studioName = document.getElementById("studioName").value;
email = document.getElementById("email").value;
password = document.getElementById("password").value;
firstName = document.getElementById("firstName").value;
lastName = document.getElementById("lastName").value;
address = document.getElementById("address").value;
country = document.getElementById("country").value;
state = document.getElementById("state").value;
city = document.getElementById("city").value;
zip = document.getElementById("zip").value;
phoneNumber = document.getElementById("phoneNumber").value;
console.log(studioName, firstName, email);
firebase
.database()
.ref("/studiopick/studio/users" + studioName)
.update({
//studioName : studioName,
firstName : firstName,
lastName : lastName,
email : email,
password : password,
address : address,
country : country,
state : state,
city : city,
zip : zip,
phoneNumber : phoneNumber
});
document.getElementById("studioName").value ="";
document.getElementById("email").value ="";
document.getElementById("password").value ="";
document.getElementById("firstName").value ="";
document.getElementById("lastName").value ="";
document.getElementById("address").value ="";
document.getElementById("country").value ="";
document.getElementById("state").value ="";
document.getElementById("city").value ="";
document.getElementById("zip").value ="";
document.getElementById("phoneNumber").value ="";
alert("Data Updated");
};
對於你的第一個問題:
您正在使用auth.currentUser
屬性而不是從onAuthStateChanged
返回的user
根據文檔:
import { getAuth, onAuthStateChanged } from "firebase/auth";
const auth = getAuth();
onAuthStateChanged(auth, (user) => {
if (user) {
// User is signed in, see docs for a list of available properties
// https://firebase.google.com/docs/reference/js/firebase.User
const uid = user.uid;
// ...
} else {
// User is signed out
// ...
}
});
如果user
從onAuthStateChanged
成功返回,您可以全局設置返回用戶的值以在整個應用程序中訪問它。 否則,您可以導航到 /login(或等效項)。
對於您的第二個問題:這取決於您如何構建數據庫。 通常的做法是使用 Firebase Auth Id 作為 users/,然后可以從 user.uid 引用。
如果您想記錄誰創建或最后編輯了一個文檔,您可以保留包含用戶 ID 的字段。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.