Gergő Nagy
Gergő Nagy

Reputation: 55

Get data from Firestore asynchronously and pass as a property in React

It's been days since I started solving this problem, read lots of stackoverflow and other pages, but none of them helped me out.
So my task is pretty easy, but maybe I make it difficult. I just want to pass data from Firestore to a React component as an array of objects, but I can't do that, even if I tried functional components with Hooks, or class based components.
I don't know why this code won't work. Just showing loading, but do not re-render.

class App extends Component {
  constructor(props) {
    super(props);
    this.state = {
        item: '' // input value
    };
    
    this.productHandler = this.productHandler.bind(this);
}

  productHandler() {
    const items = [];
    firebase.firestore()
    .collection("products")
    .get()
    .then((querySnapshot) => {
      querySnapshot.forEach(function(doc) {
          items.push(doc.data());
      });
      this.setState({items : items});
  })
  .catch(function(error) {
      console.log("Error getting documents: ", error);
  });
  }

  render(){
    if(this.state.items) {
  return (
    <div>
      <Products products={this.state.items}/>
    </div>
    );
    }else{
      return <div>Loading...</div>;
    }
}
}

Upvotes: 0

Views: 103

Answers (1)

Ethan Lipkind
Ethan Lipkind

Reputation: 1156

the code you posted looks fine, except you aren't calling productHandler anywhere. You could call it in componentDidMount and then once this.state.items updates it should cause a re-render.

Upvotes: 1

Related Questions