首页 > 解决方案 > 为什么输入数据未添加到 Firebase Firestore 集合中

问题描述

我正在使用 firebase 构建一个聊天应用程序并做出反应。面临的问题是输入数据没有被添加到 firebase firestore 集合中。该集合被命名为消息。输出就像输入正在显示并消失,因为它没有保存在数据库中。代码如下:

import React, { useRef, useState } from 'react';
import './App.css';

import firebase from 'firebase/app';
import 'firebase/firestore';
import 'firebase/auth';
import 'firebase/analytics';

import { useAuthState } from 'react-firebase-hooks/auth';
import { useCollectionData } from 'react-firebase-hooks/firestore';

firebase.initializeApp({
  //firebase_credentials
})

const auth = firebase.auth();
const firestore = firebase.firestore();


function App() {

  const [user] = useAuthState(auth);

  return (
    <div className="App">
      <header>
        <h1>SuperChat </h1>
        <SignOut />
      </header>

      <section>
        {user ? <ChatRoom /> : <SignIn />}
      </section>

    </div>
  );
}

function SignIn() {

  const signInWithGoogle = () => {
    const provider = new firebase.auth.GoogleAuthProvider();
    auth.signInWithPopup(provider);
  }

  return (
    <>
      <button className="sign-in" onClick={signInWithGoogle}>Sign in with Google</button>
      <p>Don't wait, messages are gonna disappear in a while</p>
    </>
  )

}

function SignOut() {
  return auth.currentUser && (
    <button className="sign-out" onClick={() => auth.signOut()}>Sign Out</button>
  )
}


function ChatRoom() {
  const dummy = useRef();
  const messagesRef = firestore.collection('messages');
  const query = messagesRef.orderBy('createdAt').limit(25);

  const [messages] = useCollectionData(query, { idField: 'id' });

  const [formValue, setFormValue] = useState('');


  const sendMessage = async (e) => {
    e.preventDefault();

    const { uid, photoURL } = auth.currentUser;

    await messagesRef.add({
      text: formValue,
      createdAt: firebase.firestore.FieldValue.serverTimestamp(),
      uid,
      photoURL
    })

    setFormValue('');
    dummy.current.scrollIntoView({ behavior: 'smooth' });
  }

  return (<>
    <main>

      {messages && messages.map(msg => <ChatMessage key={msg.id} message={msg} />)}

      <span ref={dummy}></span>

    </main>

    <form onSubmit={sendMessage}>

      <input value={formValue} onChange={(e) => setFormValue(e.target.value)} placeholder="say something nice" />

      <button type="submit" disabled={!formValue}>send</button>

    </form>
  </>)
}


function ChatMessage(props) {
  const { text, uid, photoURL } = props.message;

  const messageClass = uid === auth.currentUser.uid ? 'sent' : 'received';

  return (<>
    <div className={`message ${messageClass}`}>
      <img src={photoURL || 'https://feedback.seekingalpha.com/s/cache/ff/f2/fff2493e0063ac43f7161be10e0d7fff.png'} />
      <p>{text}</p>
    </div>
  </>)
}


export default App

标签: reactjsfirebasegoogle-cloud-firestorechat

解决方案


问题是您没有在方法中正确设置要作为文档添加到 Firestore 中的对象messagesRef.add()。如果您查看此文档,您可以看到该add()方法应具有如下结构:

db.collection("collectionName").add({
    field1: "someValue1",
    field2: "someValue2",
    ...
    fieldN: "someValueN"
})

因此,您应该在代码中执行以下操作:

await messagesRef.add({
  text: formValue,
  createdAt: firebase.firestore.FieldValue.serverTimestamp(),
  photoURL : "someURLvalue"
})

注意:我从上面的示例中取出了 uid,因为使用add()ID 是自动生成的。


推荐阅读