Bird
Raised Fist0
React Nativemobile~20 mins

Firestore CRUD operations in React Native - Practice Problems & Coding Challenges

Choose your learning style10 modes available
Challenge - 5 Problems
🎖️
Firestore Mastery
Get all challenges correct to earn this badge!
Test your skills under time pressure!
❓ ui_behavior
intermediate
2:00remaining
What happens when this Firestore document is deleted?
Consider this React Native code snippet that deletes a Firestore document. What will be the result in the app UI after the deletion succeeds?
React Native
import { doc, deleteDoc } from 'firebase/firestore';
import { db } from './firebaseConfig';

async function deleteUserDoc(userId) {
  const docRef = doc(db, 'users', userId);
  await deleteDoc(docRef);
  console.log('User deleted');
}

// Called on button press: deleteUserDoc('abc123');
ANothing happens because deleteDoc only marks the document for deletion but does not remove it.
BThe user document is marked as deleted but still visible in the UI until app restart.
CThe document is copied to a backup collection before deletion, so UI shows both original and backup.
DThe user document with ID 'abc123' is removed from Firestore and the UI updates to no longer show that user.
Attempts:
2 left
💡 Hint
Deleting a document removes it immediately from Firestore and listeners update the UI.
📝 Syntax
intermediate
2:00remaining
Which option correctly adds a new Firestore document with auto-generated ID?
You want to add a new document to the 'tasks' collection with a field 'title' set to 'Buy milk'. Which code snippet does this correctly?
A
import { collection, setDoc } from 'firebase/firestore';
const tasksRef = collection(db, 'tasks');
await setDoc(tasksRef, { title: 'Buy milk' });
B
import { collection, addDoc } from 'firebase/firestore';
const tasksRef = collection(db, 'tasks');
await addDoc(tasksRef, { title: 'Buy milk' });
C
import { doc, setDoc } from 'firebase/firestore';
const tasksRef = doc(db, 'tasks');
await setDoc(tasksRef, { title: 'Buy milk' });
D
import { addDoc } from 'firebase/firestore';
await addDoc('tasks', { title: 'Buy milk' });
Attempts:
2 left
💡 Hint
Use addDoc with a collection reference to add with auto ID.
❓ lifecycle
advanced
2:00remaining
What is the effect of this Firestore listener in a React Native component?
This code sets up a Firestore listener inside a React Native component. What happens when the component unmounts?
React Native
import { useEffect, useState } from 'react';
import { collection, onSnapshot } from 'firebase/firestore';
import { db } from './firebaseConfig';

function TaskList() {
  const [tasks, setTasks] = useState([]);

  useEffect(() => {
    const unsubscribe = onSnapshot(collection(db, 'tasks'), (snapshot) => {
      setTasks(snapshot.docs.map(doc => ({ id: doc.id, ...doc.data() })));
    });
    return () => unsubscribe();
  }, []);

  return null;
}
AThe listener is removed when the component unmounts, preventing memory leaks.
BThe listener continues running even after unmount, causing duplicate updates.
CThe listener throws an error on unmount because unsubscribe is not a function.
DThe listener pauses but does not unsubscribe, so it resumes on remount.
Attempts:
2 left
💡 Hint
Returning unsubscribe from useEffect cleans up the listener.
🔧 Debug
advanced
2:00remaining
Why does this Firestore update code fail with a runtime error?
This code tries to update a Firestore document but throws an error. What is the cause?
React Native
import { doc, updateDoc } from 'firebase/firestore';
import { db } from './firebaseConfig';

async function updateUser(userId) {
  const userRef = doc(db, 'users', userId);
  await updateDoc(userRef, { age: 30 });
}

updateUser('nonexistentId');
AupdateDoc fails because the document with 'nonexistentId' does not exist in Firestore.
BupdateDoc fails because the 'age' field is missing in the document.
CupdateDoc fails because doc() requires a fourth argument specifying the collection.
DupdateDoc fails because updateDoc only works with setDoc, not doc references.
Attempts:
2 left
💡 Hint
updateDoc requires the document to exist before updating.
🧠 Conceptual
expert
2:00remaining
How does Firestore handle offline writes in React Native apps?
When a React Native app writes data to Firestore while offline, what happens to the data and UI?
AWrites are queued on the server and only appear in the UI after syncing.
BWrites fail immediately and show an error in the UI until connection is restored.
CWrites are saved locally and immediately reflected in the UI; they sync to Firestore when online.
DWrites are lost if offline; the app must retry manually when online.
Attempts:
2 left
💡 Hint
Firestore supports offline persistence that updates UI instantly.

Practice

(1/5)
1. What does the collection() function do in Firestore when used in React Native?
easy
A. It points to a group of documents in the database.
B. It creates a new document with data.
C. It deletes a document from the database.
D. It updates fields inside a document.

Solution

  1. Step 1: Understand Firestore data structure

    Firestore organizes data in collections which contain documents.
  2. Step 2: Role of collection()

    The collection() function points to a specific collection (group of documents) in Firestore.
  3. Final Answer:

    It points to a group of documents in the database. -> Option A
  4. Quick Check:

    collection() = points to documents group [OK]
Hint: Remember: collection() targets groups, doc() targets single items [OK]
Common Mistakes:
  • Confusing collection() with doc()
  • Thinking collection() creates data
  • Mixing update and delete operations
2. Which of the following is the correct syntax to add a new document with data to a Firestore collection named 'users'?
easy
A. await addDoc(collection(db, 'users'), {name: 'Anna', age: 25});
B. await db.collection('users').add({name: 'Anna', age: 25});
C. await setDoc(doc(db, 'users'), {name: 'Anna', age: 25});
D. await updateDoc(collection(db, 'users'), {name: 'Anna', age: 25});

Solution

  1. Step 1: Identify correct Firestore add syntax in React Native

    The addDoc function adds a new document to a collection.
  2. Step 2: Check the syntax correctness

    await addDoc(collection(db, 'users'), {name: 'Anna', age: 25}); uses addDoc(collection(db, 'users'), data) which is the correct modern syntax.
  3. Final Answer:

    await addDoc(collection(db, 'users'), {name: 'Anna', age: 25}); -> Option A
  4. Quick Check:

    Add new doc = addDoc(collection(db, 'name'), data) [OK]
Hint: Use addDoc with collection() to add new documents [OK]
Common Mistakes:
  • Using setDoc without doc() reference
  • Calling updateDoc on a collection instead of a document
  • Using deprecated syntax from older SDK versions
3. Given this code snippet, what will be logged to the console?
const docRef = doc(db, 'tasks', 'task1');
await updateDoc(docRef, {completed: true});
const docSnap = await getDoc(docRef);
console.log(docSnap.data());
medium
A. { completed: false }
B. { completed: true }
C. An error because updateDoc cannot be awaited
D. undefined

Solution

  1. Step 1: Understand updateDoc effect

    The updateDoc call sets the field completed to true in the document 'task1'.
  2. Step 2: Reading updated document data

    The getDoc fetches the updated document, so docSnap.data() returns the updated fields.
  3. Final Answer:

    { completed: true } -> Option B
  4. Quick Check:

    updateDoc changes data, getDoc reads updated data [OK]
Hint: updateDoc changes data; getDoc reads fresh data [OK]
Common Mistakes:
  • Assuming updateDoc returns data
  • Forgetting to await async calls
  • Expecting old data without re-fetching
4. Identify the error in this Firestore delete operation code:
const docRef = doc(db, 'notes', 'note1');
await deleteDoc(collection(db, 'notes', 'note1'));
medium
A. The collection path is missing a document ID.
B. doc() cannot be used to get a document reference.
C. deleteDoc must be called without await.
D. deleteDoc should receive a document reference, not a collection.

Solution

  1. Step 1: Check deleteDoc argument type

    The deleteDoc function requires a document reference, not a collection reference.
  2. Step 2: Analyze the code's argument

    The code passes collection(db, 'notes', 'note1') which is invalid because collection() does not accept a document ID.
  3. Final Answer:

    deleteDoc should receive a document reference, not a collection. -> Option D
  4. Quick Check:

    deleteDoc(docRef) not deleteDoc(collection(...)) [OK]
Hint: deleteDoc needs doc(), not collection() [OK]
Common Mistakes:
  • Passing collection() instead of doc() to deleteDoc
  • Misunderstanding collection() parameters
  • Omitting await on async calls
5. You want to update a user's profile in Firestore only if the 'age' field exists and is less than 30. Which code snippet correctly performs this conditional update?
hard
A. const docRef = doc(db, 'users', 'user1'); await updateDoc(docRef, {status: 'young'}); const docSnap = await getDoc(docRef); if (docSnap.data().age >= 30) { await deleteDoc(docRef); }
B. await updateDoc(doc(db, 'users', 'user1'), {status: 'young', age: 30});
C. const docRef = doc(db, 'users', 'user1'); const docSnap = await getDoc(docRef); if (docSnap.exists() && docSnap.data().age < 30) { await updateDoc(docRef, {status: 'young'}); }
D. const docRef = doc(db, 'users', 'user1'); await setDoc(docRef, {status: 'young'}, {merge: true});

Solution

  1. Step 1: Check for field existence and condition

    Use getDoc to read the document and verify if 'age' exists and is less than 30.
  2. Step 2: Conditionally update document

    If condition is true, call updateDoc to update the 'status' field without overwriting other data.
  3. Final Answer:

    Code snippet that reads, checks, then updates conditionally. -> Option C
  4. Quick Check:

    Read first, then update if condition true [OK]
Hint: Always read document before conditional update [OK]
Common Mistakes:
  • Updating without checking field existence
  • Using setDoc without merge causing overwrite
  • Deleting document incorrectly after update
Recommended

Ready to prove it?

Pass the test and this pattern moves unknown strong while earning +1 Grip toward your certificate.

10 questions~5 mineasy hard