0

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>
  );
}
Frank van Puffelen
  • 565,676
  • 79
  • 828
  • 807

1 Answers1

0

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:

Frank van Puffelen
  • 565,676
  • 79
  • 828
  • 807
  • thank you for your help, after adding the setCount in side the onValue I am getting the following error: Too many re-renders. React limits the number of renders to prevent an infinite loop. – Omar Altahineh Nov 15 '22 at 20:32
  • this is what I did: const [count, setCount] = useState(null); onValue(f1, (snapshot) => { const data = snapshot.val(); setCount(data); } ); – Omar Altahineh Nov 15 '22 at 20:35
  • That sounds like a new problem. If it persists, I recommend posting a new question, with its own [minimal repro](http://stackoverflow.com/help/mcve). Please read that link; the more closely you follow the guidance, the better the chances that someone can help. – Frank van Puffelen Nov 15 '22 at 20:49