[英]How do I add collections to authenticated user in firebase react js?
I am trying to add a collection to the authenticated user by the uid.我正在尝试通过 uid 向经过身份验证的用户添加一个集合。 I am storing the uid with useState but when I pass it to the the db call it return "".我使用 useState 存储 uid,但是当我将它传递给 db 时,调用它返回“”。 If i hard code something in there it works fine.如果我在那里硬编码一些东西,它工作正常。 In the console log, I can see the uid in the state but upon submit, it submits "" I am new to react so any info would be greatly appreciated.在控制台日志中,我可以看到状态中的 uid,但在提交时,它提交“”我是新来的反应所以任何信息将不胜感激。
import React, { useState } from 'react';
import firebase from 'firebase';
import { db } from '../../firebase';
import Button from '@material-ui/core/Button';
import './SignUp.css';
function SignUp({ history }) {
const [email, setEmail] = useState('');
const [password, setPassword] = useState('');
const [checkPassword, setCheckPassword] = useState('');
const [userId, setUserId] = useState('');
console.log(userId);
const handleSignUp = (e) => {
e.preventDefault();
if (password !== checkPassword) {
return alert('Passwords do not match');
}
if (!password) {
return alert('Please enter a password1');
}
firebase
.auth()
.createUserWithEmailAndPassword(email, password)
.then((user) => {
setUserId(user.user.uid);
db.collection('Users').doc(userId).set({
email: user.user.email
});
alert('User Created');
setEmail('');
setPassword('');
setCheckPassword('');
history.push('/');
})
.catch((error) => alert(error));
};
return (
<div className="signup">
<div className="signup__title">Sign Up</div>
<form onSubmit={handleSignUp}>
<div className="signup__card">
<div className="signup__cardLabel">Email</div>
<div className="signup__cardInput">
<input
type="text"
placeholder="username"
value={email}
onChange={(e) => setEmail(e.target.value)}
/>
</div>
<div className="signup__cardLabel">Password</div>
<div className="signup__cardInput">
<input
type="password"
placeholder="password"
value={password}
onChange={(e) => setPassword(e.target.value)}
/>
</div>
<div className="signup__cardLabel">Check Password</div>
<div className="signup__cardInput">
<input
type="password"
placeholder="password"
value={checkPassword}
onChange={(e) => setCheckPassword(e.target.value)}
/>
</div>
<div className="signup__button">
<Button
type="submit"
variant="contained"
color="primary"
>
Submit
</Button>
</div>
</div>
</form>
</div>
);
}
export default SignUp;
setUserId(userId)
is async so it might not be finished when you run db.collection('Users').doc(userId).set()
. setUserId(userId)
是异步的,所以当你运行db.collection('Users').doc(userId).set()
时它可能不会完成。
And in your case (at least the code I can see), you don't need to put your userId in your state.在你的情况下(至少我能看到的代码),你不需要把你的 userId 放在你的状态。
Just run db.collection('Users').doc(user.user.id).set()
instead.只需运行db.collection('Users').doc(user.user.id).set()
代替。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.