Reputation: 1087
I'm working on a React project with Cloud Firestore. I have successfully fetched data from Firestore. But I could not set state these data to state.
How can I set state these data.
class App extends Component {
constructor(props) {
super(props);
this.state = {
items: []
};
}
async componentDidMount() {
const items = [];
firebase
.firestore()
.collection("items")
.get()
.then(function(querySnapshot) {
querySnapshot.forEach(function(doc) {
items.push(doc.data());
});
});
this.setState({ items: items });
}
render() {
const items = this.state.items;
console.log("items", items);
return (
<div>
<div>
<ul>
{items.map(item => (
<li>
<span>{item.name}()</span>
</li>
))}
</ul>
</div>
);
}
}
export default App;
Upvotes: 3
Views: 2258
Reputation: 20755
You should set state like this,
firebase
.firestore()
.collection("items")
.get()
.then((querySnapshot) => { //Notice the arrow funtion which bind `this` automatically.
querySnapshot.forEach(function(doc) {
items.push(doc.data());
});
this.setState({ items: items }); //set data in state here
});
Component renders first using initial state, and initially items: []
. You must check if data present,
{items && items.length > 0 && items.map(item => (
<li>
<span>{item.name}()</span>
</li>
))}
Upvotes: 5