Property 'collection' does not exist on type 'Firestore' error in Firebase Firestore with Firebase v9 modular syntax

huangapple go评论100阅读模式
英文:

Property 'collection' does not exist on type 'Firestore' error in Firebase Firestore with Firebase v9 modular syntax

问题

我正在开发一个使用Firebase Firestore进行数据库操作的React应用程序。我最近升级到Firebase 9版本,并切换到模块化语法来导入Firebase服务。

然而,在尝试访问Firestore中的collection方法时,我遇到了一个错误。错误消息是"Property 'collection' does not exist on type 'Firestore'."

这是我的代码片段:

import React, { useRef } from "react";
import { FormEvent } from "react";
import contactcss from "./Contact.module.css";
import { FontAwesomeIcon } from "@fortawesome/react-fontawesome";
import Card from "../../components/ui/Card";
import {
  faInstagram,
  faFacebook,
  faLinkedin,
  faDiscord,
} from "@fortawesome/free-brands-svg-icons";
import emaillogo from "../../resources/email-logo.png";

import firebase from 'firebase/app';
import 'firebase/firestore';
import { getFirestore } from 'firebase/firestore';

// ...其他代码...

export async function sendData(data: any, id: string) {
  await db.collection('contact-form').doc(id).set({ content: data });
}

// ...其他代码...

我已经按照迁移指南从Firebase的模块化语法中导入了initializeApp、getFirestore、collection、doc和set,但我仍然收到这个错误。

我尝试了各种解决方案,如重新排序导入、重新检查Firebase配置和更新Firebase依赖项,但似乎没有解决这个问题。

有人能帮助我理解为什么会出现这个错误以及如何正确使用Firebase v9模块化语法访问Firestore中的collection方法吗?

非常感谢您提前的帮助!

英文:

I'm working on a React application that utilizes Firebase Firestore for database operations. I've recently upgraded to Firebase version 9 and have switched to the modular syntax to import Firebase services.

However, I encountered an error while trying to access the collection method in Firestore. The error message is "Property 'collection' does not exist on type 'Firestore'."

Here's my code snippet:

import React, { useRef } from "react";
import { FormEvent } from "react";
import contactcss from "./Contact.module.css";
import { FontAwesomeIcon } from "@fortawesome/react-fontawesome";
import Card from "../../components/ui/Card";
import {
  faInstagram,
  faFacebook,
  faLinkedin,
  faDiscord,
} from "@fortawesome/free-brands-svg-icons";
import emaillogo from "../../resources/email-logo.png";

import firebase from 'firebase/app';
import 'firebase/firestore';
import { getFirestore } from 'firebase/firestore';
//import { randomString } from "../../App";

// testing config toggle
let isTesting = true

// Your web app's Firebase configuration
// testConfig goes here
const testConfig = {
  apiKey: "AIzaSyD1Z8u6LAQDrwBAd-t-aMzoYFpgrfjFH0E",
  authDomain: "gdscusyd-test.firebaseapp.com",
  projectId: "gdscusyd-test",
  storageBucket: "gdscusyd-test.appspot.com",
  messagingSenderId: "430942619633",
  appId: "1:430942619633:web:e4b3661fac99d31cd5e650",
  measurementId: "G-DCF0X0L8QY"
};

// prodConfig goes here
const prodConfig = {
  apiKey: "AIzaSyCdgEs7mefO_Woe3UJA7lgdlrtiqjpmfCI",
  authDomain: "gdsc-usyd.firebaseapp.com",
  databaseURL: "https://gdsc-usyd-default-rtdb.firebaseio.com",
  projectId: "gdsc-usyd",
  storageBucket: "gdsc-usyd.appspot.com",
  messagingSenderId: "971303209941",
  appId: "1:971303209941:web:a6d9fa662f48a20916cb5c",
  measurementId: "G-HB1NEN3G3J"
};

let appConfig = isTesting ? testConfig : prodConfig;

// Initialize Firebase
const app = firebase.initializeApp(appConfig);

// Initialize db
const db = getFirestore(app);


// generate random string of specified length
export function randomString(length: number) {
  var result = '';
  const characters = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789';
  
for (var i = 0; i < length; i++) {
  result += characters.charAt(Math.floor(Math.random() * characters.length));
}
​
return result;
}
​

export async function sendData(data: any, id: string) {
  await db.collection('contact-form').doc(id).set({ content: data });
}

​
const processData = async (event: FormEvent) => {
event.preventDefault();
​
// @ts-ignore
const elementsArray = [...event.target.elements];
​
const data = elementsArray.reduce((acc, element) => {
  if (element.id) {
    acc[element.id] = element.value;
  }
​
  return acc;
}, {});

try {
  if (data.name === '') throw("Name cannot be left empty")
  if (data.email === '') throw("Email cannot be left empty")
  if (data.message === '') throw("Message cannot be left empty")
​
  await sendData(data, randomString(10))
}
}

function Contact() {
  return (
    <div>
      <div>
        <div className={contactcss.background}>
          <img
            className={contactcss.emaillogo}
            src={emaillogo}
            alt="Contact Us"
          />
          <div className={contactcss.contact}>Contact Us</div>
        </div>
      </div>

      <Card
        title="We're keen to hear from you!"
        imageUrl="https://images.app.goo.gl/D6m6hHMnP1gjsKKV7"
        body=""
        /* onSubmitForm={submitFormHandler} */ // Placeholder comment
      />

      <div className={contactcss.whitebackground}>
        <div className={contactcss.socials}>
          <h1>Follow Our Socials</h1>
          <p className={contactcss.socialmedia}>
            Stay connected with GDSC USYD by following us on our social media
            channels:
          </p>
          <div>
            <a href="https://www.instagram.com/gdscusyd/">
              <FontAwesomeIcon
                className={contactcss.instagram}
                icon={faInstagram}
              />
            </a>

            <a href="https://www.facebook.com/gdsc.usyd">
              <FontAwesomeIcon
                className={contactcss.facebook}
                icon={faFacebook}
              />
            </a>

            <a href="https://discord.com/channels/872033047652990986/872033047652990989">
              <FontAwesomeIcon
                className={contactcss.discord}
                icon={faDiscord}
              />
            </a>

            <a href="https://www.linkedin.com/company/gdsc-usyd/">
              <FontAwesomeIcon
                className={contactcss.linkedin}
                icon={faLinkedin}
              />
            </a>
          </div>
        </div>
      </div>
    </div>
  );
};

export default Contact;

I have imported initializeApp, getFirestore, collection, doc, and set from Firebase's modular syntax as per the migration guide, but I'm still getting the error.

I've tried various solutions such as reordering the imports, rechecking my Firebase configuration, and updating my Firebase dependencies, but none seem to resolve the issue.

Could someone please help me understand why I'm getting this error and how I can properly access the collection method in Firestore with Firebase v9 modular syntax?

Thank you in advance for any assistance!

答案1

得分: 1

你需要将你的路由包裹在一个<Switch>标签内。

你的路由应该像这样:

<Switch>
    <Route exact path="/" component={Home} />
    <Route path="/users" component={Users} />
</Switch>

请尝试这样做。

英文:

You have to wrap your Routes into a &lt;Switch&gt; Tag.

Your routes should look like this;

&lt;Switch&gt;
    &lt;Route exact path=&quot;/&quot;&gt;
       &lt;Home /&gt;
    &lt;/Route&gt;
    &lt;Route path=&quot;/users&quot;&gt;
       &lt;Users /&gt;
    &lt;/Route&gt;
&lt;/Switch&gt;

try this.

答案2

得分: 0

这是您要翻译的代码部分:

import AllMeetupsPage from './pages/AllMeetups';
import NewMeetupPage from './pages/NewMeetup';

import React from 'react';
import { render } from 'react-dom';
import { BrowserRouter, Routes, Route } from "react-router-dom";

class App extends React.Component {	
   constructor(props) {
   super(props);

   this.state = {};
 }

 render(){
   return (
     <BrowserRouter>
       <Routes>
         <Route path="/" element={<AllMeetupsPage />}/>
         <Route path="/new-meetup/" element={<NewMeetupPage />}/>
       </Routes>
     </BrowserRouter>   
   )
 }
}

render(<App></App>, document.querySelector('#root'));

export default App;

如果您需要进一步的帮助,请随时告诉我。

英文:

Maybe you can try this version in your app.js file (and please add your code as text, not image) :

import AllMeetupsPage from &#39;./pages/AllMeetups&#39;;
import NewMeetupPage from &#39;./pages/NewMeetup&#39;;

import React from &#39;react&#39;;
import { render } from &#39;react-dom&#39;;
import { BrowserRouter, Routes, Route } from &quot;react-router-dom&quot;;

class App extends React.Component {	
   constructor(props) {
   super(props);

   this.state = {};
 }

 render(){
   return (
     &lt;BrowserRouter&gt;
       &lt;Routes&gt;
         &lt;Route path=&quot;/&quot; element={&lt;AllMeetupsPage /&gt;}/&gt; 
         &lt;Route path=&quot;/new-meetup/&quot; element={&lt;NewMeetupPage /&gt;}/&gt; 
       &lt;/Routes&gt;
     &lt;/BrowserRouter&gt;   
   )
 }
}

render(&lt;App&gt;&lt;/App&gt;, document.querySelector(&#39;#root&#39;));

export default App;

答案3

得分: -1

你需要将你的路由包装在<Routes>标签中。

英文:

You have to wrap your Routes into a &lt;Routes&gt; Tag.

huangapple
  • 本文由 发表于 2023年3月7日 13:12:25
  • 转载请务必保留本文链接:https://go.coder-hub.com/75658245.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定