Reactjs 将用户ID名称添加到firebase
你好, 我想将名字和用户ID添加到firebase数据库(集合用户)。 用户ID是在验证表单后生成的(正确生成-我已选中),不幸的是,db中的“User”集合只显示没有用户ID的名字。。 看起来表单过早地捕获了ID,实际上ID为null 全部:Reactjs 将用户ID名称添加到firebase,reactjs,firebase,firebase-realtime-database,Reactjs,Firebase,Firebase Realtime Database,你好, 我想将名字和用户ID添加到firebase数据库(集合用户)。 用户ID是在验证表单后生成的(正确生成-我已选中),不幸的是,db中的“User”集合只显示没有用户ID的名字。。 看起来表单过早地捕获了ID,实际上ID为null 全部: import React,{useCallback,useState}来自“React”; 从“react router”导入{withRouter}; 从“/base”导入应用程序; 从“firebase”导入*作为firebase; 常量注册=({h
import React,{useCallback,useState}来自“React”;
从“react router”导入{withRouter};
从“/base”导入应用程序;
从“firebase”导入*作为firebase;
常量注册=({history})=>{
const[currentUser,setCurrentUser]=useState(null);
const[firstname,setName]=useState(“”);
const[lastname,setLastName]=useState(“”);
const handleSignUp=useCallback(
异步(事件)=>{
event.preventDefault();
const{email,password}=event.target.elements;
试一试{
等待应用程序
.auth()
.createUserWithEmailAndPassword(email.value,password.value)
.那么(
等待firebase.auth().onAuthStateChanged((用户)=>{
如果(用户){
setCurrentUser(user.uid);
}
console.log(当前用户);
})
)
.那么(
(等待firebase.database().ref('user').push()).set({user:currentUser,firstname:firstname})
);
history.push(“/”)
}捕获(错误){
警报(错误);
}
},
[当前用户、名字、历史记录]
);
const insertDetails=async()=>{
等待firebase.auth().onAuthStateChanged((用户)=>{
如果(用户){
setCurrentUser(user.uid);
}
});
};
返回(
注册
伊米
setName(e.target.value)}/>
纳兹维斯科
setLastName(e.target.value)}/>
电子邮件
哈斯
注册
);
};
使用路由器导出默认值(注册);
有人能告诉我如何解决这个问题吗?
谢谢 我很快在您的代码中发现了一些问题:
currentUser
对象,但设置状态是一个异步操作push()
为新用户生成一个随机密钥,而我强烈建议使用UID作为用户密钥wait
与then
混合使用,这通常不是一个好主意app.auth()
.createUserWithEmailAndPassword(email.value, password.value)
.then(
firebase.auth().onAuthStateChanged((user) => {
if (user) {
setCurrentUser(user.uid);
firebase.database().ref('user').child(currentUser).set({ user: currentUser, firstname: firstname })
}
})
)
app.auth()
.createUserWithEmailAndPassword(email.value, password.value)
.then(
firebase.auth().onAuthStateChanged((user) => {
if (user) {
setCurrentUser(user.uid);
firebase.database().ref('user').child(currentUser).set({ user: currentUser, firstname: firstname })
}
})
)