I am quite bit new to react native and to front end development in general, so please bear with me. I am writing a simple react native app that Retrieves data of map markers from firebase and display them on a map. I wrote a python program that adds new markers to firebase regularly, which means that the data stored on the database is not static. I followed this documentation from google and reading data through an event listener works fine in my app, but I couldn’t store the data of the object inside a variable out of onValue. My question is how to get the retrieved data from the database, and display it on the map view?
here is my code:
import React, { useEffect, useState } from 'react'
import { FlatList, Keyboard, Text, TextInput, TouchableOpacity, View, Dimensions} from 'react-native'
import styles from './styles';
import MapView from 'react-native-maps';
import { Marker } from "react-native-maps";
import { getDatabase, ref, onValue } from 'firebase/database';
import { firebase} from '../../firebase/config'
import { app} from '../../firebase/config'
export default function HomeScreen(props) {
const db = getDatabase();
const f1 = ref(db, '/');
onValue(f1, (snapshot) => {
const data = snapshot.val();
});
const uniRegion = {
latitude: 25.2863943,
longitude: 55.4749801,
latitudeDelta: 0.0922,
}
return (
<View style={styles.container}>
<MapView style={styles.map} region={uniRegion}
showsUserLocation={true} >
<Marker coordinate={uniRegion} />
</MapView >
</View>
);
}
You can store the data in any variable you want, but need to make sure that React re-renders its UI when the data is loaded or updated. To do that, you'll want to use store the data in the state using a useState
hook.
For some examples of this: