Emil Botezatu
Emil Botezatu

Reputation: 15

React Native fetching data from Firebase does not work

I have a home screen that is used to load the feed from a collection made in Firebase. The firebase config is for web and it is in another file and it's working fine. The strange thing is that when I delete the method call, it works but when I refresh the home screen is blank. Also the firestore is working fine and the post and comments are uploading successfully. What could be the problem?

  const HomeScreen = () => {
    
  const [posts, setPosts] = useState(null);
  const [loading, setLoading] = useState(true);

    
  const fetchPosts = async() => {
    try {
      const list = [];
      await firebase.firestore();
      db.collection('posts')
      .get()
      .then((querySnapshot) => {
          querySnapshot.forEach((doc) => {
            const {userId, post, postImg, postTime, likes, comments} = doc.data();
            list.push({
            id: doc.id,
            userId,
            userName: 'Test name',
            userImg: require('../assets/users/user-7.jpg'),
            postTime: postTime,
            post,
            postImg,
            liked: false,
            likes,
            comments,
          })
          })
      })

      setPosts(list);

      if(loading) {
        setLoading(false);
      }

      console.log('Posts', list);
    } catch(e) {
      console.log(e);
    }
  }
  useEffect(() => {
    fetchPosts();
  }, [])
   
    

    return (
        <Container>
            <FlatList
                data={posts}
                renderItem={({item}) => <PostCard item={item} />}
                keyExtractor={(item) => item.id}
                showsVerticalScrollIndicator={false}
            />
        </Container>
    );
}

Upvotes: 0

Views: 50

Answers (1)

Dharmaraj
Dharmaraj

Reputation: 50830

setPosts will be ran before your promise is resolved. Your function is async so why not use await instead of promise chaining as shown:

const fetchPosts = async () => {
  try {
    const list = [];
    const db = firebase.firestore()
  
    const querySnapshot = await db.collection('posts').get()
    querySnapshot.docs.forEach((doc) => {
      const {userId, post, postImg, postTime, likes, comments} = doc.data();
      list.push({
        id: doc.id,
        userId,
        userName: 'Test name',
        userImg: require('../assets/users/user-7.jpg'),
        postTime: postTime,
        post,
        postImg,
        liked: false,
        likes,
        comments,
      })
    })

    setPosts(list);

    if(loading) {
      setLoading(false);
    }
  } catch (e) {
    console.log(e)
  }
}

Upvotes: 1

Related Questions