FirebaseError:函数CollectionReference.doc()要求其第一个参数的类型为非空字符串,但



我正在register函数中的firebase中创建一个电子邮件帐户,然后创建一个profile集合来存储配置文件信息,如配置文件图像、firstName、lastName等。

目前,当我点击注册按钮时,我收到了这个错误:

FirebaseError:函数CollectionReference.doc((要求其第一个参数的类型为非空字符串,但它是:未定义的``

我相信之所以会发生这种情况,是因为firebase创建users集合的速度不够快,当我尝试创建profile集合时,它会出现错误,因为它找不到用户集合。

我应该使用异步函数吗?

function Register() {
const history = useHistory();
const [email, setEmail] = useState("");
const [username, setUsername] = useState("");
const [password, setPassword] = useState("");
const [image, setImage] = useState("");
const [firstName, setFirstName] = useState("");
const [lastName, setLastName] = useState("");
const [user, setUser] = useState("");
const register = (e) => {
e.preventDefault();
auth
.createUserWithEmailAndPassword(email, password)
.then((auth) => {
// it successfully created a new user with email and password
if (auth) {
history.push("/dashboard");
}
})
.catch((error) => alert(error.message));
db.collection("users").doc(user?.uid).collection("profile").add({
image: image,
firstName: firstName,
lastName: lastName,
username: username,
});
};

这是您调用doc((的代码行:

db.collection("users").doc(user?.uid).collection("profile").add({

请注意,您可能将undefined传递给doc()。如果user为null或未定义,则会发生这种情况。这可能是因为createUserWithEmailAndPassword是异步的,不会立即完成。如果你想在创建帐户后做一些事情,你应该在then回调中做。

auth
.createUserWithEmailAndPassword(email, password)
.then((credential) => {
db.collection("users").doc(credential.user.uid).collection("profile").add({
image: image,
firstName: firstName,
lastName: lastName,
username: username,
});
history.push("/dashboard");
})

最新更新