javascript 这是我的代码,但我得到了错误:TypeError:firestore.collection不是函数

lyr7nygr  于 2023-08-02  发布在  Java
关注(0)|答案(1)|浏览(87)
//OtherInfo.js
import React, { useState } from "react";
import DateOfBirthPicker from "./DateOfBirthPicker";
import { getFirestore, collection, doc, updateDoc } from "firebase/firestore";
import firebaseApp from "./firebaseConfig"; // Import the Firebase configuration

export function formatDOB(date) {
  // The formatDOB function remains the same
}

function OtherInfo({ formData, setFormData }) {
  const handleDateChange = (date) => {
    // Handle the date selection here
    console.log("Selected date:", date);
    setFormData({ ...formData, dob: date }); // Save the selected date in the formData state

    // Save to Firestore
    const firestore = getFirestore(firebaseApp); // Pass the Firebase instance to getFirestore

    firestore
      .collection("users") // Replace "users" with the name of your collection
      .doc("dob") // Replace "userDocumentId" with the ID of the user document in Firestore, or use .add() to create a new document
      .update({ dob: formatDOB(date) }) // Format the date before saving to Firestore
      .then(() => {
        console.log("Date of Birth successfully saved to Firestore!");
      })
      .catch((error) => {
        console.error("Error saving Date of Birth to Firestore:", error);
      });
  };

  return (
    <div className="other-info-container">
      <label htmlFor="dob">Date of Birth:</label>
      <DateOfBirthPicker // Use the DateOfBirthPicker component
        selectedDate={formData.dob}
        onDateChange={handleDateChange}
      />
    </div>
  );
}

export default OtherInfo;

字符串
我正在往firebase里添加数据。相反,它给出了一个错误:TypeError:firestore.collection不是函数。在这种情况下,有人能帮助我吗?在这种情况下,我使用firebase作为数据库。

vmdwslir

vmdwslir1#

从版本8开始,firebase的API发生了变化。不是集合对象有你链接在一起的方法,你导入函数并调用它们。
这个密码

firestore
  .collection("users")
  .doc("dob")
  .update({ dob: formatDOB(date) })

字符串
……现在是这样做的:

import { collection, doc, updateDoc } from 'firebase/firestore'

const ref = doc(collection('users'), 'dob');
updateDoc(ref, { dob: formatDOB(date) });


如果您正在查看firestore的文档(例如,关于添加数据的this documentation),请确保在示例中选择“Web模块化API”,以查看版本8+的格式。“Web命名空间的API”显示了旧的风格

相关问题