简体   繁体   中英

Cannot create a document inside the firebase collection

I am trying to create a simple to-do app using firebase as my CMS. But I am facing an error while trying to create my document on the firewall. My code is,

const addToDo = (e) => {
e.preventDefault();

addDoc(collection(db, "todos"), {
  inprogress: true,
  timestamp: firebase.firestore.FieldValue.serverTimestamp(),
  todo: todoInput,
})
setTodoInput("");

}

So I try to call this function once I click the button on the form,

    <form>
      <TextField
        id="standard-basic"
        label="Write a Todo"
        variant="standard"
        className="textField"
        value={todoInput}
        onChange={(e) => {
          setTodoInput(e.target.value);
        }} />
      <Button 
        type="submit" 
        variant="contained" 
        onClick={addToDo} 
        className="buttonDisplay">
        Display
        </Button>
    </form>

When I click the button I get an error on the console saying that "Uncaught TypeError: Cannot read properties of undefined (reading 'FieldValue')."

Here I have also attached the import for my App.js,

import './App.css';
import { TextField, Button } from '@material-ui/core';
import { useState } from 'react';
import {db} from './firebase_cofig';
import firebase from 'firebase/compat/app';
import { collection, addDoc } from "firebase/firestore";

And this is my firebase_config.js file,

import { initializeApp } from "firebase/app";
import { getFirestore } from "firebase/firestore";

const firebaseConfig = {
  apiKey: "AIzaSyAVa9YdtqQAYuZ0u5stifRRhp5RULHLnRc",
  authDomain: "to-do-app-fd528.firebaseapp.com",
  projectId: "to-do-app-fd528",
  storageBucket: "to-do-app-fd528.appspot.com",
  messagingSenderId: "646758689416",
  appId: "1:646758689416:web:0c91670c0caa3d08b34d3d"
};

// Initialize Firebase
const app = initializeApp(firebaseConfig);

// const db = firebase.firestore();
const db = getFirestore(app);

export { db };

can someone help me on this issue?

The syntax for Server Timestamp has changed with the JS SDK version 9.

You need to adapt your code to:

import { ..., serverTimestamp } from 'firebase/firestore';

addDoc(collection(db, "todos"), {
  inprogress: true,
  timestamp: serverTimestamp(),
  todo: todoInput,
})

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM