FireStore-实时数据-使用onSnapshot时遇到问题

时间:2020-06-24 19:58:51

标签: reactjs google-cloud-firestore react-hooks

使用以下组件,我可以连接到Cloud FireStore集合并将新文档添加到其中。

现在,我正在尝试通过onSnapshot方法使用实时数据,但是我不确定如何在我的代码中实现它。

import React, { useState } from 'react';
import { db } from '../firebase';

const AddCard = ({ totalDoclNumbers }) => {
  const [newOriginalText, setNewOriginalText] = useState([]);
  const [newTranslatedText, setNewTranslatedText] = useState([]);
  const nextNumber = totalDoclNumbers + 1;

  const onAdd = async () => {
    await db.collection('FlashCards').add({
      originalText: newOriginalText,
      translatedText: newTranslatedText,
      customId: Number(nextNumber)
    });

  };

  return (
    <ul className='list'>
      <li className='list__item list__item--add' key={nextNumber}>
        <input
          type='text'
          defaultValue={nextNumber}
        />
        <div>
            <textarea
              onChange={(e) => setNewOriginalText(e.target.value)}
            />
          )}
        </div>
        <textarea
          onChange={(e) => setNewTranslatedText(e.target.value)}
        />
        <button onClick={onAdd}>
          Add
        </button>
      </li>
    </ul>
  );
};

export default AddCard;

这是我尝试过的:

import React, { useState, useEffect } from 'react';
import { db } from '../firebase';

const AddCard = ({ totalDoclNumbers }) => {
  const [newOriginalText, setNewOriginalText] = useState([]);
  const [newTranslatedText, setNewTranslatedText] = useState([]);
  const nextNumber = totalDoclNumbers + 1;

  const onAdd = async () => {
    await db
      .collection('FlashCards')
      .add({
        originalText: newOriginalText,
        translatedText: newTranslatedText,
        customId: Number(nextNumber),
      })
      .onSnapshot((snapshot) => {
        let changeds = snapshot.docChanges();
        changeds.forEach((change) => {
          if (change.type === 'added') {
            renderDocList();
          }
        });
      });
  };

  const renderDocList = () => {
    return (
      <ul>
        <li key={nextNumber}>
          <input
            type='text'
            defaultValue={nextNumber}
          />
          <div>
              <textarea
                onChange={(e) => setNewOriginalText(e.target.value)}
              />
            )}
          </div>
          <textarea
            onChange={(e) => setNewTranslatedText(e.target.value)}
          />
          <button onClick={onAdd}>
            Add
          </button>
        </li>
      </ul>
    );
  };

  return (
    <>
      {renderDocList()}
    </>
  );
};

export default AddCard;

但是,一旦我点击“添加”按钮,就会出现此错误:

未处理的拒绝(TypeError): firebase__WEBPACK_IMPORTED_MODULE_1 _。db.collection(...)。add(...)。onSnapshot不是函数

1 个答案:

答案 0 :(得分:0)

onSnapshot无法与添加配合使用。想法是您要订阅该收藏,以便每当发生更改时它就会告诉您。

所以您需要这样做

import React, { useState, useEffect } from 'react';
import { db } from '../firebase';
  db.collection('FlashCards')
     .onSnapshot((snapshot) => {
        let changeds = snapshot.docChanges();
        changeds.forEach((change) => {
          if (change.type === 'added') {
            renderDocList();
          }
        });
  });
  const AddCard = ({ totalDoclNumbers }) => {
  const [newOriginalText, setNewOriginalText] = useState([]);
  const [newTranslatedText, setNewTranslatedText] = useState([]);
  const nextNumber = totalDoclNumbers + 1;

  const onAdd = async () => {
    await db
      .collection('FlashCards')
      .add({
        originalText: newOriginalText,
        translatedText: newTranslatedText,
        customId: Number(nextNumber),
      })
  };

  const renderDocList = () => {
    return (
      <ul>
        <li key={nextNumber}>
          <input
            type='text'
            defaultValue={nextNumber}
          />
          <div>
              <textarea
                onChange={(e) => setNewOriginalText(e.target.value)}
              />
            )}
          </div>
          <textarea
            onChange={(e) => setNewTranslatedText(e.target.value)}
          />
          <button onClick={onAdd}>
            Add
          </button>
        </li>
      </ul>
    );
  };

  return (
    <>
      {renderDocList()}
    </>
  );
};

export default AddCard;

您可以找到其他示例here