I'm coding in React Native and need to get a value from Google Firebase in real time. I am able to get the value (1), but when the value in the database changes, the textbox in my application does not change accordingly (2). In other words, real-time synchronization with the database is not implemented. I can't figure out why. Will you help me with this problem? Thank you so much! The code I wrote is as follows:
import React, { useState } from 'react'; import { View, Text, TextInput} from 'react-native'; import { NavigationContainer } from '@react-navigation/native'; import { createNativeStackNavigator } from '@react-navigation/native-stack'; import { ImageBackground, StyleSheet, Pressable, Image } from 'react-native'; import { Slider } from '@react-native-assets/slider' import { Linking } from 'react-native' import database from '@react-native-firebase/database'; var Data = ""; function Room({ navigation, route }) { //(1) database() .ref('/esp01_1/id') .on('value', snapshot => { console.log('data from firebase: ', snapshot.val()); Data = snapshot.val() }); return ( <View style={styles.container}> //(2) <Text style={styles.text}>{Data}</Text> </View> ); }
I need to get a value from Google Firebase in real time, and when it changes in the database, I need it to change in the textbox as well.
P粉6708387352023-09-14 14:28:02
This is because data is loaded from Firebase (and pretty much any modern cloud API) asynchronously, and is not yet available when your <Text style={styles.text}>{Data}</Text>
is executed.
You'll want to:
The common way to do this is by using the useState
and useEffect
hooks.
const [data, setData] = useState(); // Putting the code to load from Firebase in a useEffect call // with no dependencies (the empty array at the end) ensure it // only runs once, when the component is first rendered. useEffect(() => { database() .ref('/esp01_1/id') .on('value', snapshot => { // Calling setData puts the data in the component's state // and tells ReactJS to rerender the UI. setData(snapshot.val()); }); }, []);
This is a quite complex topic, so I recommend reading up on both of the hooks used here and also see: