RefirebaseRefirebase

runTransaction

Execute a set of reads and writes atomically.

Overview

The runTransaction method allows you to execute operations atomically. If a document read within the transaction is modified by a concurrent operation, the transaction will automatically retry. All reads (tx.get) must occur before any writes (tx.set, tx.update, tx.delete).

Running a transaction
import { db } from 'refirebase';

try {
  await db.firestore.runTransaction(async (tx) => {
    // Read the current balance
    const userDoc = await tx.get('users', 'user123');
    if (!userDoc) throw new Error('User not found');
    
    const newBalance = (userDoc.balance || 0) + 50;

    // Update the balance
    tx.update('users', 'user123', { balance: newBalance });
    
    // Log the transaction
    tx.set('transactions', 'tx456', { amount: 50, type: 'credit' });
  });
  console.log('Transaction completed successfully!');
} catch (error) {
  console.error('Transaction failed: ', error);
}

Parameters

ParamTypeDescription
fn*(tx: FirestoreTransaction) => Promise<T>An async callback function containing the transaction operations.

Return value

Returns

Promise<T>

Returns the result of the callback function. Throws an error if the transaction fails.