首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >onSnapshot firebase,getServerSideProps

onSnapshot firebase,getServerSideProps
EN

Stack Overflow用户
提问于 2022-01-02 00:17:17
回答 2查看 554关注 0票数 0

我的代码

代码语言:javascript
复制
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数据库中获取实时数据,在快照中,我可以得到结果,但是当它在数组之外时,它是空的,我不能传递给道具。

EN

回答 2

Stack Overflow用户

发布于 2022-01-06 06:09:06

我不使用onSnapshot,而是使用getDocs (您需要从‘firebase/firestore’导入):

代码语言:javascript
复制
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,
        },
    };
};
票数 0
EN

Stack Overflow用户

发布于 2022-09-11 09:25:16

我也遇到了同样的问题。在这里,我们应该使用get()而不是快照,因为接下来我们将处理幕后更新的数据。

所以像这样重写你的代码

代码语言:javascript
复制
export async function getServerSideProps(context) {
  const resultref = await db.collection("books").get();
  const results = resultRef.docs.map((doc)=>({
    id: doc.id,
    resultData: doc.data()
  }))
  return {
    props: { books:  JSON.parse(JSON.stringify(results)) },
  }
}

因此map函数将返回变量结果中的新数组,然后将其作为支持进行深度复制和传递。

我希望这能给你带来预期的结果。

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/70552803

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档