我无法使用 firebase firestore 将数据存储到数据库
I can't store data to database using firebase firestore
我花了几个小时试图弄清楚为什么我无法在用户注册创建帐户时存储他们的名字和姓氏。
代码是 运行,用户可以创建一个帐户。电子邮件已成功通过 firebase 的身份验证,但甚至没有在 firebase 中创建该集合。有人知道为什么吗?
Signup.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
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;
您似乎在将数据保存到数据库(通过调用 database.student.add(...)
)之前离开组件(通过调用 navigate("/dashboard")
)。
为防止这种情况,将添加数据的代码移到导航代码之前:
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");
}
我也在数据库调用中添加了一个 await
,这样导航只会在数据添加到数据库后发生。如果您有一个 single-page 应用程序,这不是严格需要的,但它可能有助于查看代码中的流程。
我花了几个小时试图弄清楚为什么我无法在用户注册创建帐户时存储他们的名字和姓氏。
代码是 运行,用户可以创建一个帐户。电子邮件已成功通过 firebase 的身份验证,但甚至没有在 firebase 中创建该集合。有人知道为什么吗?
Signup.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
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;
您似乎在将数据保存到数据库(通过调用 database.student.add(...)
)之前离开组件(通过调用 navigate("/dashboard")
)。
为防止这种情况,将添加数据的代码移到导航代码之前:
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");
}
我也在数据库调用中添加了一个 await
,这样导航只会在数据添加到数据库后发生。如果您有一个 single-page 应用程序,这不是严格需要的,但它可能有助于查看代码中的流程。