skip to Main Content

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


  1. Chosen as BEST ANSWER

    ok, now it works fine! thanks a lot for helping me!


  2. 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:

    1. Store the data in the state of your component
    2. Tell ReactJS to rerender the component when the state changes

    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:

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search