【发布时间】:2021-05-28 01:19:21
【问题描述】:
你好, 我想将名字和用户 ID 添加到 firebase 数据库(集合用户)。 验证表单后生成用户 ID(正确生成 - 我检查了),不幸的是 db 中的“用户”集合仅显示没有用户 ID 的名字.. 看起来表单捕获 ID 过早,实际上 ID 为空
全部:
import React, { useCallback, useState } from 'react';
import { withRouter } from 'react-router';
import app from './base';
import * as firebase from 'firebase';
const SignUp = ({ history }) => {
const [ currentUser, setCurrentUser ] = useState(null);
const [ firstname, setName ] = useState('');
const [ lastname, setLastName ] = useState('');
const handleSignUp = useCallback(
async (event) => {
event.preventDefault();
const { email, password } = event.target.elements;
try {
await app
.auth()
.createUserWithEmailAndPassword(email.value, password.value)
.then(
await firebase.auth().onAuthStateChanged((user) => {
if (user) {
setCurrentUser(user.uid);
}
console.log(currentUser);
})
)
.then(
(await firebase.database().ref('user').push()).set({ user: currentUser, firstname: firstname })
);
history.push('/')
} catch (error) {
alert(error);
}
},
[currentUser, firstname, history]
);
const insertDetails = async () => {
await firebase.auth().onAuthStateChanged((user) => {
if (user) {
setCurrentUser(user.uid);
}
});
};
return (
<div>
<h1>Sign up</h1>
<form onSubmit={handleSignUp}>
<label>
Imie
<input name="firstname" value={firstname} type="text" onChange={(e) => setName(e.target.value)} />
</label>
<label>
Nazwisko
<input name="lastName" value={lastname} type="text" onChange={(e) => setLastName(e.target.value)} />
</label>
<label>
Email
<input name="email" type="email" placeholder="Email" />
</label>
<label>
Hasło
<input name="password" type="password" placeholder="Password" />
</label>
<button type="submit" onClick={insertDetails}>
Sign Up
</button>
</form>
</div>
);
};
export default withRouter(SignUp);
有人可以告诉我如何解决它吗? 谢谢!
【问题讨论】:
标签: reactjs firebase firebase-realtime-database