Firestore CRUD operations let you create, read, update, and delete data in your app's database. This helps your app save and manage information easily.
Firestore CRUD operations in React Native
import { getFirestore, collection, addDoc, getDocs, updateDoc, deleteDoc, doc } from 'firebase/firestore'; const db = getFirestore(); // Create await addDoc(collection(db, 'collectionName'), { field: 'value' }); // Read const querySnapshot = await getDocs(collection(db, 'collectionName')); querySnapshot.forEach(doc => console.log(doc.id, doc.data())); // Update const docRef = doc(db, 'collectionName', 'docId'); await updateDoc(docRef, { field: 'newValue' }); // Delete await deleteDoc(docRef);
Use collection() to point to a group of documents.
Use doc() with an ID to point to a specific document.
await addDoc(collection(db, 'users'), { name: 'Alice', age: 25 });
const snapshot = await getDocs(collection(db, 'users')); snapshot.forEach(doc => console.log(doc.id, doc.data()));
const userRef = doc(db, 'users', 'abc123'); await updateDoc(userRef, { age: 26 });
const userRef = doc(db, 'users', 'abc123'); await deleteDoc(userRef);
This React Native app connects to Firestore and shows a list of users. You can add a new user, update the first user's age, or delete the first user. The list updates automatically after each action.
import React, { useEffect, useState } from 'react'; import { View, Text, Button, FlatList } from 'react-native'; import { initializeApp } from 'firebase/app'; import { getFirestore, collection, addDoc, getDocs, updateDoc, deleteDoc, doc } from 'firebase/firestore'; const firebaseConfig = { apiKey: 'your-api-key', authDomain: 'your-auth-domain', projectId: 'your-project-id', storageBucket: 'your-storage-bucket', messagingSenderId: 'your-messaging-sender-id', appId: 'your-app-id' }; const app = initializeApp(firebaseConfig); const db = getFirestore(app); export default function FirestoreCRUD() { const [users, setUsers] = useState([]); const fetchUsers = async () => { const querySnapshot = await getDocs(collection(db, 'users')); const usersList = []; querySnapshot.forEach(doc => { usersList.push({ id: doc.id, ...doc.data() }); }); setUsers(usersList); }; const addUser = async () => { await addDoc(collection(db, 'users'), { name: 'New User', age: 20 }); fetchUsers(); }; const updateFirstUser = async () => { if (users.length === 0) return; const userRef = doc(db, 'users', users[0].id); await updateDoc(userRef, { age: users[0].age + 1 }); fetchUsers(); }; const deleteFirstUser = async () => { if (users.length === 0) return; const userRef = doc(db, 'users', users[0].id); await deleteDoc(userRef); fetchUsers(); }; useEffect(() => { fetchUsers(); }, []); return ( <View style={{ flex: 1, padding: 20 }}> <Button title="Add User" onPress={addUser} /> <Button title="Update First User Age" onPress={updateFirstUser} /> <Button title="Delete First User" onPress={deleteFirstUser} /> <FlatList data={users} keyExtractor={item => item.id} renderItem={({ item }) => ( <Text>{item.name} - Age: {item.age}</Text> )} /> </View> ); }
Always handle errors in real apps to avoid crashes.
Firestore operations are asynchronous, so use async/await or promises.
Remember to set up Firebase config and initialize the app before using Firestore.
Firestore CRUD lets you create, read, update, and delete data in your app.
Use collection() and doc() to point to data locations.
Always fetch fresh data after changes to keep UI updated.
Practice
collection() function do in Firestore when used in React Native?Solution
Step 1: Understand Firestore data structure
Firestore organizes data in collections which contain documents.Step 2: Role of
Thecollection()collection()function points to a specific collection (group of documents) in Firestore.Final Answer:
It points to a group of documents in the database. -> Option AQuick Check:
collection()= points to documents group [OK]
- Confusing collection() with doc()
- Thinking collection() creates data
- Mixing update and delete operations
Solution
Step 1: Identify correct Firestore add syntax in React Native
TheaddDocfunction adds a new document to a collection.Step 2: Check the syntax correctness
await addDoc(collection(db, 'users'), {name: 'Anna', age: 25}); usesaddDoc(collection(db, 'users'), data)which is the correct modern syntax.Final Answer:
await addDoc(collection(db, 'users'), {name: 'Anna', age: 25}); -> Option AQuick Check:
Add new doc = addDoc(collection(db, 'name'), data) [OK]
- Using setDoc without doc() reference
- Calling updateDoc on a collection instead of a document
- Using deprecated syntax from older SDK versions
const docRef = doc(db, 'tasks', 'task1');
await updateDoc(docRef, {completed: true});
const docSnap = await getDoc(docRef);
console.log(docSnap.data());Solution
Step 1: Understand updateDoc effect
TheupdateDoccall sets the fieldcompletedto true in the document 'task1'.Step 2: Reading updated document data
ThegetDocfetches the updated document, sodocSnap.data()returns the updated fields.Final Answer:
{ completed: true } -> Option BQuick Check:
updateDoc changes data, getDoc reads updated data [OK]
- Assuming updateDoc returns data
- Forgetting to await async calls
- Expecting old data without re-fetching
const docRef = doc(db, 'notes', 'note1'); await deleteDoc(collection(db, 'notes', 'note1'));
Solution
Step 1: Check deleteDoc argument type
ThedeleteDocfunction requires a document reference, not a collection reference.Step 2: Analyze the code's argument
The code passescollection(db, 'notes', 'note1')which is invalid because collection() does not accept a document ID.Final Answer:
deleteDoc should receive a document reference, not a collection. -> Option DQuick Check:
deleteDoc(docRef) not deleteDoc(collection(...)) [OK]
- Passing collection() instead of doc() to deleteDoc
- Misunderstanding collection() parameters
- Omitting await on async calls
Solution
Step 1: Check for field existence and condition
UsegetDocto read the document and verify if 'age' exists and is less than 30.Step 2: Conditionally update document
If condition is true, callupdateDocto update the 'status' field without overwriting other data.Final Answer:
Code snippet that reads, checks, then updates conditionally. -> Option CQuick Check:
Read first, then update if condition true [OK]
- Updating without checking field existence
- Using setDoc without merge causing overwrite
- Deleting document incorrectly after update
Ready to prove it?
Pass the test and this pattern moves unknown
