【问题标题】:onSnapshot firebase, getServerSidePropsonSnapshot 火力基地,getServerSideProps
【发布时间】:2022-01-02 00:17:17
【问题描述】:

my code

export const getServerSideProps: GetServerSideProps = async () => {
  const ref = collection(db, "books");
  const results = [];

  const unsub = onSnapshot(ref, (snapshot) => {
    snapshot.forEach((doc) => {
      results.push({ ...doc.data(), id: doc.id });
    });
    //here i get the results
    console.log(results)
  });

  // here is empty
  console.log(results)

  return {
    props: {
      books: results,
    },
  };
};

我正在尝试通过 getServerSideProps 函数从 firestore 数据库中获取实时数据,在快照内我可以获得结果,但是当它在数组之外时,它是空的,我无法传递给道具。

【问题讨论】:

标签: reactjs firebase google-cloud-firestore next.js server-side-rendering


【解决方案1】:

我会使用 getDocs 代替 onSnapshot(你需要从 'firebase/firestore' 导入):

export const getServerSideProps: GetServerSideProps = async () => {
    const [results, setResults] = useState([]);
    const ref = collection(db, 'books');
    const snapshot = await getDoc(docRef);
    articlesSnapshot.forEach((doc) => {
        setResults((oldArray) => [...oldArray, doc.data()]);
    });
    return {
        props: {
          books: results,
        },
    };
};

【讨论】:

    猜你喜欢
    • 2016-09-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-06-05
    • 2016-08-03
    • 2021-05-04
    相关资源
    最近更新 更多