0
0
React Nativemobile~5 mins

Firestore CRUD operations in React Native

Choose your learning style9 modes available
Introduction

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.

Saving user profile information after signup
Showing a list of items fetched from the database
Updating user settings or preferences
Removing outdated or unwanted data from the app
Syntax
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.

Examples
Adds a new user named Alice with age 25 to the 'users' collection.
React Native
await addDoc(collection(db, 'users'), { name: 'Alice', age: 25 });
Reads all users and prints their IDs and data.
React Native
const snapshot = await getDocs(collection(db, 'users'));
snapshot.forEach(doc => console.log(doc.id, doc.data()));
Updates the age of the user with ID 'abc123' to 26.
React Native
const userRef = doc(db, 'users', 'abc123');
await updateDoc(userRef, { age: 26 });
Deletes the user with ID 'abc123' from the database.
React Native
const userRef = doc(db, 'users', 'abc123');
await deleteDoc(userRef);
Sample App

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.

React Native
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>
  );
}
OutputSuccess
Important Notes

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.

Summary

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.