开发者问题收集

FireBaseError:使用无效数据调用函数 addDoc()。运行 react 时不支持的字段值:未定义

2022-04-06
1719

我正在尝试将数据添加到 Firebase 数据库。在执行此操作时,我收到此错误:“FireBaseError:使用无效数据调用的函数 addDoc()。不支持的字段值:未定义”。注册表单需要 2 个输入:姓名和电子邮件。函数 handleSubmit 将从表单中获取输入的姓名和电子邮件,并将其中的 addDoc 函数添加到数据库。 FirebaseConfig.js 包含 Firebase 的所有配置。

Registration.js

import React, {useState} from 'react'
import { TextField, Button } from '@mui/material'
//import { getAuth } from 'firebase/auth'
import { collection, addDoc } from 'firebase/firestore'
import { app, database } from './firebaseConfig'
//import {getDatabase, set, ref } from 'firebase/database'

export default function Registration() {
    //let auth=getAuth()
    let collectionRef = collection(database, "users")
    const [data, setdata] = useState({});

    const handleInput = (event) => {
        let newInput = {[event.target.value] : event.target.value}
        setdata({...data, ...newInput});
    }

    const handleSubmit = () => {
        
        addDoc(collectionRef, {
            name: data.name,
            email: data.email
        }).then(()=>{
            alert('Data added successfully!');
        }).catch((err)=>{
            alert(err.message);
        });

    }
  return (
    <div>
        <form>
            <h1>Registration Form</h1>
            <TextField id="filled-basic" label="Name" name='name' variant="filled" onChange={(event)=>(handleInput(event))} /><br/><br/>
            <TextField id="filled-basic" label="Email" name='email' variant="filled" onChange={(event)=>(handleInput(event))}/><br/><br/>
            <Button variant='contained' color='success' onClick={(e)=>(handleSubmit(e))}>Submit</Button>
        </form>
    </div>
  )
}

FirebaseConfig.js

// Import the functions you need from the SDKs you need
import { initializeApp } from "firebase/app";
import { getAnalytics } from "firebase/analytics";
import {getFirestore} from "firebase/firestore"
// TODO: Add SDKs for Firebase products that you want to use
// https://firebase.google.com/docs/web/setup#available-libraries

// Your web app's Firebase configuration
// For Firebase JS SDK v7.20.0 and later, measurementId is optional
const firebaseConfig = {
  apiKey: ...,
  authDomain: ...,
  projectId: ...,
  storageBucket: ...,
  messagingSenderId: ...,
  appId: ...,
  measurementId: ...
};

// Initialize Firebase
export const app = initializeApp(firebaseConfig);
const analytics = getAnalytics(app);
export const database = getFirestore(app);
2个回答

姓名或电子邮件似乎未定义。请尝试添加条件来检查,如下所示:

const handleSubmit = () => {
  console.log(data);
  if (data.name && data.email) {
    addDoc(collectionRef, {
      name: data.name,
      email: data.email
    }).then(() => {
      alert('Data added successfully!');
    }).catch((err) => {
      alert(err.message);
    });
  } else {
    console.log("Invalid data")
  }
}
Dharmaraj
2022-04-06

我发现了错误。在 Registration.js 中,应该是 let newInput = {[event.target.name] : event.target.value> ,而不是 let newInput = {[event.target.value] : event.target.value> 。 感谢阅读 :)

Aditya Bikram Arandhara
2022-04-06