read data from firebase realtime database using react native

424 Views Asked by At

I want to read data from firebase realtime database.

I want to fix my "function readData()" like,

If I use this funcion, I want to read my data, without enter "username".

for example, I created this,

username:hello, email:[email protected]

and If I press "read data" button, (without enter 'username') I want to read recent data. (username and email both)

please help me!

this is my app.js

import { StatusBar } from 'expo-status-bar';
import { useState } from 'react';
import { Button, button, StyleSheet, Text, TextInput, View } from 'react-native';
import { ref, set, update, onValue, remove } from "firebase/database";
import { db } from './components/config';


export default function App() {

  const [username, setName] = useState('');
  const [email, setEmail] = useState('');



  function createData() {

    set(ref(db, 'users/' + username), {          
      username: username,
      email: email  
    }).then(() => {
      // Data saved successfully!
      alert('data created!');    
  })  
      .catch((error) => {
          // The write failed...
          alert(error);
      });
}


  function update() {

    set(ref(db, 'users/' + username), {
      username: username,
      email: email  
    }).then(() => {
      // Data saved successfully!
      alert('data updated!');    
  })  
      .catch((error) => {
          // The write failed...
          alert(error);
      });
}

  
  function readData() {

    const starCountRef = ref(db, 'users/' + username);
    onValue(starCountRef, (snapshot) => {
      const data = snapshot.val();

      setEmail(data.email);   

    });

  }



  return (
    <View style={styles.container}>
      <Text>firebase</Text>
      <TextInput value={username} onChangeText={(username) => {setName(username)}} placeholder='Username' style={styles.TextBoxes}></TextInput>
      <TextInput value={email} onChangeText={(email) => {setEmail(email)}} placeholder='Email' style={styles.TextBoxes}></TextInput>
      <Button title='create data' onPress={createData}></Button>
      <Button title='update data' onPress={update}></Button>
      <Button title='read data' onPress={readData}></Button>
    </View>
  );
}

const styles = StyleSheet.create({
  container: {
    flex: 1,
    backgroundColor: '#fff',
    alignItems: 'center',
    justifyContent: 'center',
  },
  TextBoxes: {
    width:'90%',
    fontSize:18,
    padding:12,
    backgroundColor:'grey',
    marginVertical:10,
  }
});
1

There are 1 best solutions below

1
Güray On

I understand you want to call last username by default if username is empty. For this, you can define lastUserName state and call it if username is empty, for example;

 const [lastUserName, setLastUserName] = useState('');

readData() ,

function readData() {

    const starCountRef = ref(db, 'users/' + username !== '' ? username : lastUserName);
    onValue(starCountRef, (snapshot) => {
      const data = snapshot.val();

      setEmail(data.email);   

    });

  }

Then, view should be like that;

<View style={styles.container}>
      <Text>firebase</Text>
      <TextInput value={username} 
      onChangeText={(username) => {
          setName(username)
          setLastUserName(username) // add this line
        }
      } 
      placeholder='Username' style={styles.TextBoxes}></TextInput>
      <TextInput value={email} onChangeText={(email) => {setEmail(email)}} placeholder='Email' style={styles.TextBoxes}></TextInput>
      <Button title='create data' onPress={createData}></Button>
      <Button title='update data' onPress={update}></Button>
      <Button title='read data' onPress={readData}></Button>
    </View>

Note : If you want to keep this state in global use Redux.

Note: Use localStorage if you want the application to run on the same state after closing and reopening. see: https://github.com/react-native-async-storage/async-storage