9 Commands Cheat sheet Firestore Firebase
Here are the basic commands or cheat sheets for Firestore on Firebase for React Native, these are made to make it easier as a reference for coding and teaching training.
1. Add firebase library di project : yarn firebase
yarn firebase
2. Configure Firebase config.js
Go to the firebase website, and create a new account. Once logged in, create a new project in the Firebase Console. Enable Email & Password authentication method Create a new web type application with the name com.testing.app Copy the Firebase JSON configuration and place it in firebaseConfig in the following config.js fileimport * as firebase from 'firebase';
import '@firebase/auth';
import '@firebase/firestore';
const firebaseConfig = {
apiKey: '',
authDomain: '',
databaseURL: '',
projectId: '',
storageBucket: '',
messagingSenderId: '',
appId: '',
};
if (!firebase.apps.length) {
firebase.initializeApp(firebaseConfig);
}
export { firebase };
3. Create a user with email and password and save it in the users collection
const onRegisterPress = () => {
if (password !== confirmPassword) {
alert("Passwords don't match.")
return
}
firebase
.auth()
.createUserWithEmailAndPassword(email, password)
.then((response) => {
const uid = response.user.uid
const data = {
id: uid,
email,
fullName,
};
const usersRef = firebase.firestore().collection('users')
usersRef
.doc(uid)
.set(data)
.then(() => {
navigation.navigate('Home', {user: data})
})
.catch((error) => {
alert(error)
});
})
.catch((error) => {
alert(error)
});
}
4. Example login using email and password
import { firebase } from '../../firebase/config'
const onLoginPress = () => {
firebase
.auth()
.signInWithEmailAndPassword(email, password)
.then((response) => {
const uid = response.user.uid
const usersRef = firebase.firestore().collection('users')
usersRef
.doc(uid)
.get()
.then(firestoreDocument => {
if (!firestoreDocument.exists) {
alert("User does not exist anymore.")
return;
}
const user = firestoreDocument.data()
navigation.navigate('Home', {user: user})
})
.catch(error => {
alert(error)
});
})
.catch(error => {
alert(error)
})
}
5. Check the status of the logged in user using onAuthStateChanged
useEffect(() => {
const usersRef = firebase.firestore().collection('users');
firebase.auth().onAuthStateChanged(user => {
if (user) {
usersRef
.doc(user.uid)
.get()
.then((document) => {
const userData = document.data()
setLoading(false)
setUser(userData)
})
.catch((error) => {
setLoading(false)
});
} else {
setLoading(false)
}
});
}, []);
6. Filtering data by userID and sorting the createdAt column
const [entities, setEntities] = useState([])
const entityRef = firebase.firestore().collection('entities')
const userID = 1
entityRef
.where("authorID", "==", userID)
.orderBy('createdAt', 'desc')
.onSnapshot(
querySnapshot => {
const newEntities = []
querySnapshot.forEach(doc => {
const entity = doc.data()
entity.id = doc.id
newEntities.push(entity)
});
setEntities(newEntities)
},
error => {
console.log(error)
}
)
7. Save data with server time
const onAddButtonPress = () => {
if (entityText && entityText.length > 0) {
const timestamp = firebase.firestore.FieldValue.serverTimestamp();
const data = {
text: entityText,
authorID: userID,
createdAt: timestamp,
};
entityRef
.add(data)
.then(_doc => {
setEntityText('')
Keyboard.dismiss()
})
.catch((error) => {
alert(error)
});
}
}
8. Delete row
await firebase.firestore().collection('entities')
.doc(id)
.delete()
.then(function () {
Alert.alert('Record successfully deleted!');
})
.catch(function (error) {
Alert.alert('Error removing transaction: ', error);
});
9. Update data
a. Update all fields
const entityRef = firebase.firestore().collection("entities");
entityRef.set({
text: "text data",
authorID: userID,
createdAt: timestamp,
});
b. Update certain field
const entityRef = firebase.firestore().collection("entities");
// To update text and authorID only:
entityRef.doc(uid)
.update({
text: "text data",
authorID: userID,
})
.then(function () {
console.log("Document successfully updated!");
});
References:
https://www.freecodecamp.org/news/react-native-firebase-tutorial/
https://github.com/instamobile/react-native-firebase/