I am coding in react native, and I need to pick up a value from realtime google firebase. I am able to get the value (1), but when it changes on the db, it does not in the text field on my app (2). in other words, it is not synchronized in real time with the db. I can not figure out why. could you help me with it? thanks a lot! the code I have wrote down is:
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 pick up a value from realtime google firebase, and when it changes on the db, I need that it changes in the text field, as well
2
Answers
ok, now it works fine! thanks a lot for helping me!
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
anduseEffect
hooks.This is a quite complex topic, so I recommend reading up on both of the hooks used here and also see: