jesus fernandez
jesus fernandez

Reputation: 369

how to bring all the pictures from a collection in firebase?

I am following the documentation in Firebase, I am able to post pictures and they get to my collection (Pictures) but I cannot get them back, I do not get any error or so but It never gets to the console log in the get method, this is the code which is basically done following the documentation:

import React, { Component } from "react";
import firebase, { firestore } from "firebase";
const firebaseConfig = {
  apiKey: "AIzaSyBaYaChURjABW6kNE0D5yQaIU88RxhFAL4",
  authDomain: "jammer-documents.firebaseapp.com",
  databaseURL: "https://jammer-documents.firebaseio.com",
  projectId: "jammer-documents",
  storageBucket: "jammer-documents.appspot.com",
  messagingSenderId: "74638218427",
  appId: "1:74638218427:web:8ce7ba1fc2f8de7d4bc59e"
};
firebase.initializeApp(firebaseConfig);

export default class Pictures extends Component {
  state = {
    photos: []
  };
  componentDidMount() {
    let images = [];
    firebase
      .firestore()
      .collection("Pictures")
      .get()
      .then(function(querySnapshot) {
        querySnapshot.forEach(function(doc) {
          let imageData = {
            url: doc.data().url,
            created: doc.data().added
          };
          images.push(imageData);
        });
      });
    console.log("images", images);
    console.log(this.state.photos);
    this.setState({ photos: images });
    console.log(this.state.photos);
  }
  render() {
    const items = this.state.photos;

    return (
      <div className="container-fluid pt-3">
        <div className="card-columns">
          {items.map(i => (
            <div className="card">
              <img className="card-img-top materialboxed" src={i.url} alt="" />
            </div>
          ))}
        </div>
      </div>
    );
  }
}



Upvotes: 0

Views: 86

Answers (1)

Elliot Hesp
Elliot Hesp

Reputation: 523

The block of code inside of componentDidMount is async, so the setState is being called straight away. You need to set state after the request has returned, and after you have looped over each document:

  let images = [];
    firebase
      .firestore()
      .collection("Pictures")
      .get()
      .then((querySnapshot) => {
        querySnapshot.forEach(function(doc) {
          let imageData = {
            url: doc.data().url,
            created: doc.data().added
          };
          images.push(imageData);
        });

        this.setState({ photos: images });
      });

Upvotes: 2

Related Questions