如何在react js中使用firestore数据库?第一次使用 Firebase

问题描述 投票:0回答:1

My Code

我认为这是旧的做法,但我正在遵循一个教程,其中一个人正在这样做,但我不知道如何修复错误:(


import { db } from "../../firebase";
const Feed = () => {
  
  const [posts, setPosts] = useState([]);
  
    useEffect(() => {
    db.collection("posts").onSnapshot((snapshot) =>
      setPosts(
        snapshot.docs.map((doc) => ({
          id: doc.id,
          data: doc.data(),
        }))
      )
    );
  }, []);
  return (
    <div className="feed">
      {posts.map((post) => {
        <Post />;
      })}
    </div>
  );
};

export default Feed;

我想使用firestore数据库,我是第一次在我的项目中使用Firebase,请帮助我:)

javascript reactjs firebase google-cloud-firestore
1个回答
0
投票
    import React, { useState, useEffect } from 'react';
import { db } from '../../firebase'; 

const Feed = () => {
  const [posts, setPosts] = useState([]);
  const [isLoading, setIsLoading] = useState(true); 
  useEffect(() => {
    const unsubscribe = db.collection("posts").onSnapshot((snapshot) => {
      const updatedPosts = snapshot.docs.map((doc) => ({
        id: doc.id,
        data: doc.data(),
      }));
      setPosts(updatedPosts);
      setIsLoading(false); 
    }, (error) => {
      
      setIsLoading(false); 
    });

    return unsubscribe; 
  }, []);

  return (
    <div className="feed">
      {isLoading ? (
        <p>Loading posts...</p>
      ) : (
        posts.map((post) => (
          <Post key={post.id} post={post.data} /> 
        ))
      )}
    </div>
  );
};

export default Feed;
© www.soinside.com 2019 - 2024. All rights reserved.