9 Perintah Cheat sheet Firestore Firebase
Berikut adalah perintah – perintah dasar atau cheat sheet untuk Firestore di Firebase untuk React Native, ini dibuat agar memudahkan sebagai referensi untuk coding dan pengajaran training.
1. Add firebase library di project : yarn firebase
yarn firebase
2. Konfigurasi Firebase config.js
Buka website firebase, dan buat akun baru.
Setelah masuk, buat proyek baru di Console Firebase.
Aktifkan metode autentikasi Email & Password
Buat aplikasi baru tipe web dengan nama com.testing.app
Salin konfigurasi JSON Firebase dan letakkan di firebaseConfig di file config.js berikut
import * 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. Buat user dengan email dan password dan menyimpannya di collection users
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. Contoh login menggunakan email dan 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. Mengecek status user yang sedang login menggunakan 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. Men-filter data berdasarkan userID dan sorting kolom createdAt
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. Menyimpan data dengan waktu server
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. Hapus data
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 keseluruhan field
const entityRef = firebase.firestore().collection("entities");
entityRef.set({
text: "text data",
authorID: userID,
createdAt: timestamp,
});
b. Update field tertentu
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!");
});
Sumber :
https://www.freecodecamp.org/news/react-native-firebase-tutorial/