[英]I can't store data to database using firebase firestore
I've been spending several hours trying to figure out why I can't store the first name and last name of a user when they sign up to create an account.我花了几个小时试图弄清楚为什么我无法在用户注册创建帐户时存储他们的名字和姓氏。
The code is running and the user are able to create an account.代码正在运行,用户可以创建一个帐户。 The email is successfully authenticated to firebase, however the collection is not even created in firebase. Does anybody know why?
email 已成功通过 firebase 的身份验证,但是在 firebase 中甚至没有创建集合。有人知道为什么吗?
Signup.js注册.js
import React, { useRef, useState } from "react"
import { Form, Button, Card, Alert, Container } from "react-bootstrap"
import { Link, useNavigate } from "react-router-dom"
import { database } from "../firebase"
import { useAuth } from "../contexts/AuthContext"
export default function Signup() {
const [firstName, setfirstName] = useState("")
const [lastName, setlastName] = useState("")
const { currentUser } = useAuth()
const emailRef = useRef();
const passwordRef = useRef();
const passwordConfirmRef = useRef();
const { signup } = useAuth();
const [error, setError] = useState("");
const [loading, setLoading] = useState(false);
const navigate = useNavigate();
async function handleSubmit(e) {
e.preventDefault()
if (passwordRef.current.value !== passwordConfirmRef.current.value) {
return setError("The password does not match!");
}
try {
setError("");
setLoading(true);
await signup(emailRef.current.value, passwordRef.current.value);
navigate("/dashboard");
} catch {
setError("Failed to create an account");
}
//this is where its suppose to handle storing data to firebase with the collection from firebase.js that I had created
database.student.add({
firstName: firstName,
lastName: lastName,
userId: currentUser.uid,
createdAt: database.getCurrentTimestamp(),
})
setfirstName("")
}
return (
<Container
className="d-flex align-items-center justify-content-center"
style={{ minHeight: "100vh" }}
>
<div className="w-100" style={{ maxWidth: "400px" }}>
<Card>
<Card.Body>
<h2 className="text-center mb-4">Sign Up Here</h2>
{error && <Alert variant="danger">{error}</Alert>}
<Form onSubmit={handleSubmit}>
<Form.Group>
<Form.Label>First Name</Form.Label>
<Form.Control
type="text"
required
value={firstName}
onChange={e => setfirstName(e.target.value)}
/>
</Form.Group>
<Form.Group>
<Form.Label>Last Name</Form.Label>
<Form.Control
type=""
required
value={lastName}
onChange={e => setlastName(e.target.value)}
/>
</Form.Group>
<Form.Group id="email">
<Form.Label>Email</Form.Label>
<Form.Control type="email" ref={emailRef} required />
</Form.Group>
<Form.Group id="password">
<Form.Label>Password</Form.Label>
<Form.Control type="password" ref={passwordRef} required />
</Form.Group>
<Form.Group id="pass-confirm">
<Form.Label>Password Confirmation</Form.Label>
<Form.Control
type="password"
ref={passwordConfirmRef}
required
/>
</Form.Group>
<Button disabled={loading} className="w-100" type="submit">
Sign up
</Button>
</Form>
</Card.Body>
</Card>
<div className="w-100 text-center mt-2">
Do you have an account? <Link to="/login">Login Here</Link>
</div>
</div>
</Container>
)
}
firebase.js firebase.js
import firebase from 'firebase/compat/app';
import 'firebase/compat/firestore';
import 'firebase/compat/auth';
import 'firebase/compat/functions';
import "firebase//compat/storage";
const app = firebase.initializeApp( {
apiKey: process.env.REACT_APP_FIREBASE_API_KEY,
authDomain: process.env.REACT_APP_FIREBASE_AUTH_DOMAIN,
projectId: process.env.REACT_APP_FIREBASE_PROJECT_ID,
storageBucket: process.env.REACT_APP_FIREBASE_STORAGE_BUCKET,
messagingSenderId: process.env.REACT_APP_FIREBASE_MESSAGING_SENDER_ID,
appId: process.env.REACT_APP_FIREBASE_APP_ID,
})
const firestore = app.firestore()
export const database = {
student: firestore.collection("student"),
teacher: firestore.collection("teacher"),
getCurrentTimestamp: firebase.firestore.FieldValue.serverTimestamp,
}
export const auth = app.auth()
export const functions = app.functions()
export const storage = app.storage()
export default app;
You seem to be navigating away from the component (by calling navigate("/dashboard")
) before the data is saved to the database (by calling database.student.add(...)
).在将数据保存到数据库(通过调用
database.student.add(...)
)之前,您似乎正在离开组件(通过调用navigate("/dashboard")
)。
To prevent this, move the code that adds the data before the code that navigates:为防止这种情况,请将添加数据的代码移到导航代码之前:
try {
setError("");
setLoading(true);
await signup(emailRef.current.value, passwordRef.current.value);
// 👇
await database.student.add({
firstName: firstName,
lastName: lastName,
userId: currentUser.uid,
createdAt: database.getCurrentTimestamp(),
})
navigate("/dashboard");
} catch {
setError("Failed to create an account");
}
I added an await
to the database call too, so that the navigation only happens after the data was added to the database.我也在数据库调用中添加了一个
await
,以便导航仅在数据添加到数据库后发生。 This is not strictly needed if you have a single-page application, but it may help seeing the flow of things in your code.如果你有一个单页应用程序,这不是严格需要的,但它可能有助于查看代码中的事物流。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.