Retrieving/Handling Image URL From Firestore - React Native

Viewed 1058

I am new to React Native and Firebase (Firestore) and I'm developing an app where I have to retrieve posts to my feed.

I can retrieve all data I need, but I don't know how to display the image in the frontend. The post document has a field image which is saved as an URL and stored in the Firebase storage.

Does anyone know how can I get the image displayed? I am using a to sort the data.

This is my retrieveData() and it prints the correct URL:

  retrieveData() {
    var that = this;
    let postRef = firebase
      .firestore()
      .collection("posts")
      .orderBy("timestamp", "desc")
      .limit(10);
    let allPosts = postRef
      .get()
      .then((snapshot) => {
        snapshot.forEach((doc) => {
          var post = that.state.posts;
          const data = (doc.id, "=>", doc.data());
          that.setState({ posts: post });
          console.log(data.image);
          post.push({
            id: data.id,
            title: data.title,
            description: data.description,
            expireDate: data.expireDate,
            timestamp: data.timestamp,
            image: data.image,
          });
        });
      })
      .catch((err) => {
        console.log("Error getting documents", err);
      });
  }

And this is how I am calling the image in the flatlist:

<Image
   source={post.image}
   style={styles.postImage}
/>

Can anyone help me with that?

Thanks in advance.

1 Answers

Can you share the image url ? And preferred way is to store image on the firebase storage and get the downloadUrl then store that url in the firestore document.

fileref.put(file)
.then(snapshot => {
   return snapshot.ref.getDownloadURL();   // Will return a promise with the download 
 link
})

.then(downloadURL => {
  console.log(`Successfully uploaded file and got download link - ${downloadURL}`);
  return downloadURL;
 })

.catch(error => {
  // Use to signal error if something goes wrong.
  console.log(`Failed to upload file and get link - ${error}`);
});
Related