Been spending over 4 hours solving this problem with no luck. I recently began learning how to code with react and javascript to create an app that allows users to add their favourite locations to a list.
I was able to connect to firestore and return the data to a state, but for some reason, I can't access it in "render()" and "return()". My console logs the values such as longitude and latitude but when I access the state through it doesn't work. Here is the code, see below for the photos
state = {
regionSet: false,
}
componentDidMount() {
Geolocation.getCurrentPosition(position => {
const { latitude, longitude } = position.coords
const region = {
...this.state.region,
latitude,
longitude,
latitudeDelta: 0.008,
longitudeDelta: 0.008,
}
this.setState({ region, regionSet: true })
})
userData = async () => {
const user = auth().currentUser;
var userRef = firestore().collection('favoritelist').doc(user.uid).collection(user.uid);
const markers = [];
await firestore().collection('favoritelist').doc(user.uid).collection(user.uid).get()
.then(querySnapshot => {
querySnapshot.docs.forEach(doc => {
markers.push(doc.data());
});});
this.setState({markers});
console.log(this.state.markers)
console.log(this.state.markers[0].lat)
};
userData()
}
render() {
const { markers } = this.state
const user = auth().currentUser;
const mapRegion = {latitude: 37.782822, longitude: -122.4067605}
return (
<View>
{console.log(markers)}
<Text>
{this.state.markers[0].lat}
</Text>
</View>
console logs the data/state perfectly fine
state doesn't work in a text and return
Thank you for reading and helping out if possible :)
So basically what's happening is your React component is getting the data from fire-store but the component is already rendered and the easiest way to fix is to change markers[0].lat to markers[0]?.lat. This will show data once its available. Hope this fix your issue