简体   繁体   English

我无法使用 firebase firestore 将数据存储到数据库

[英]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.

相关问题 我可以使用 jQuery 将数据导入 Firebase Firestore 数据库吗? - Can I import data to Firebase Firestore database using jQuery? 如何使用 Flutter、Firebase - Firestore 数据库根据日期对数据进行分组和列出? - How do I Group and List data according to date using Flutter, Firebase - Firestore Database? 如何在 Firebase 数据库中注册和存储数据 - Android Studio | Firebase - How can I Register and Store Data in Firebase Database - Android Studio | Firebase 使用 Flutter Firebase Firestore 从数据库获取地理点数据 - Getting Geopoint Data from Database Using Flutter Firebase Firestore 如何将当前用户的数据存储到 Firebase Firestore? - How to store data to Firebase Firestore for current user? 如何按顺序显示 Firebase Firestore 数据? - How can I display Firebase Firestore data in order? 如何从 Firebase Firestore 获取 ReactJs 的数据? - How Can I get data with ReactJs from Firebase Firestore? 无法将数据插入 firebase 实时数据库 - can't insert data into firebase realtime database Firebase 云功能不更新 Firestore 数据库中的数据 - Firebase Cloud function not updating data in Firestore database 使用 firebase 函数将数据添加到 firestore 数据库 - Adding data to firestore database with firebase functions
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM