To get started first follow the tutorial: React Native Firebase Authentication – Email Password Login Signup with Source code here. Then follow the below steps:
- Install the React Native Firebase “firestore” module to the root of your React Native project:
yarn add @react-native-firebase/firestore
2. Import auth module from @react-native-firebase/auth
import firestore from '@react-native-firebase/firestore';
const usersCollection = firestore().collection('Users');
3. Create Read and Write data functions:
const getUsers = () => {
usersCollection.get().then(querySnapshot => {
console.log('Total users: ', querySnapshot.size);
let userArray: any = [];
querySnapshot.forEach(documentSnapshot => {
console.log('User ID: ', documentSnapshot.id, documentSnapshot.data());
userArray.push(documentSnapshot.data());
});
setUsers(userArray);
});
};
const addUser = () => {
usersCollection
.add({
name: 'Test user 1',
})
.then(() => {
console.log('User added!');
getUsers();
});
};
4. Users.tsx screen to list users:
import React, {useEffect, useState} from 'react';
import {
Dimensions,
FlatList,
StyleSheet,
Text,
TouchableOpacity,
View,
} from 'react-native';
import firestore from '@react-native-firebase/firestore';
const usersCollection = firestore().collection('Users');
function Users(): JSX.Element {
const [users, setUsers] = useState([]);
const getUsers = () => {
usersCollection.get().then(querySnapshot => {
console.log('Total users: ', querySnapshot.size);
let userArray: any = [];
querySnapshot.forEach(documentSnapshot => {
console.log('User ID: ', documentSnapshot.id, documentSnapshot.data());
userArray.push(documentSnapshot.data());
});
setUsers(userArray);
});
};
const addUser = () => {
usersCollection
.add({
name: 'Test user 1',
})
.then(() => {
console.log('User added!');
getUsers();
});
};
useEffect(() => {
getUsers();
}, []);
return (
<View style={styles.container}>
<Text>Users ({users.length})</Text>
<FlatList
data={users}
renderItem={({item}) => <Text style={styles.item}>{item.name}</Text>}
/>
<TouchableOpacity onPress={addUser} style={styles.btnStyle}>
<Text>Add user</Text>
</TouchableOpacity>
</View>
);
}
const styles = StyleSheet.create({
container: {
display: 'flex',
justifyContent: 'flex-start',
height: Dimensions.get('window').height - 40,
paddingTop: 22,
},
item: {
padding: 10,
fontSize: 18,
height: 44,
},
btnStyle: {
width: Dimensions.get('window').width,
justifyContent: 'center',
flexDirection: 'row',
padding: 20,
backgroundColor: '#7DE24E',
borderWidth: 0,
color: '#FFFFFF',
borderColor: '#7DE24E',
},
});
export default Users;
5. Run app using below command:
npm run android
jw7aez