Reputation: 35
I am trying to get data from firestore database and display it in react a component. I have made the connection with the database. I can view the data from the database in console log. But i can't seem to update the react component state after initial construction of the component. I am new to react and can't figure out what is going on. Below is my component code.
I have tried moving the database call to the child component. And have the same issue. I have tried constructing the component with a initial state which looks like the data from the database. I have tried to remove the checks on the markers data to verify if it's undefined. And i still can't figure out what is the issue.
import React, { Component } from 'react'
import { Map, TileLayer } from 'react-leaflet'
import MarkerList from './MarkerList'
import './Basemap.css'
import firebase from '../../config/fbConfig'
class Turmap extends Component {
constructor(){
super();
this.state={
mapdata:[]
}
};
componentDidMount(){
const db = firebase.firestore();
var turmarkers =[];
db.collection("Markets").get().then((querySnapshot) => {
querySnapshot.forEach((doc) => {
turmarkers.push(doc.data())
})
}
);
this.setState({
mapdata:turmarkers
})
}
render() {
var markers = this.state.mapdata;
return (
<div>
{this.state.mapdata.length}
<Map className='map' center={[21,79]} zoom={4.3}>
<TileLayer
attribution='&copy <a href="http://osm.org/copyright">OpenStreetMap</a> contributors'
url="https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png"
/>
{this.state.mapdata.length>0 && <MarkerList markers = {markers} />}
</Map>
</div>
)
}
}
export default Turmap
There are two documents in my firestore collection. I expect after the component loads, the componentdidMount will execute setstate for mapdata. And the updated state will re render the component. But the updated state in this.state.mapdata does not re render the component. so the length of this.state.mapdata is always 0 and never changes to the amount of data present in the database which is 2.
Upvotes: 2
Views: 3726
Reputation: 12691
Move this.setState
inside your db callback (if you put it outside it will be executed before the db call have finished)
componentDidMount() {
const db = firebase.firestore();
var turmarkers =[];
db.collection("Markets").get().then((querySnapshot) => {
querySnapshot.forEach((doc) => {
turmarkers.push(doc.data())
});
this.setState({
mapdata:turmarkers
});
});
}
Upvotes: 5