0

In react-redux-firebase, how do I do a batch write similar to that shown in the firestore docs? (see below)

// Get a new write batch
var batch = db.batch();

// Set the value of 'NYC'
var nycRef = db.collection("cities").doc("NYC");
batch.set(nycRef, {name: "New York City"});

// Update the population of 'SF'
var sfRef = db.collection("cities").doc("SF");
batch.update(sfRef, {"population": 1000000});

// Delete the city 'LA'
var laRef = db.collection("cities").doc("LA");
batch.delete(laRef);

// Commit the batch
batch.commit().then(function () {
    // ...
});
Loren
  • 820
  • 2
  • 11
  • 18

1 Answers1

1

Something like this would work. Don't forget that react-redux-firebase and redux-firestore extend the original implementations of firebase and firestore respectively.

const Counter = () => {
  const firestore = useFirestore()
  const batch = firestore.batch()
  const nycRef = firestore.get({collection: 'cities', doc: 'NYC'})
  batch.set(nycRef, {name: 'New York City'})
  const sfRef = firestore.get({collection: 'cities', doc: 'SF'})
  batch.update(sfRef, {population: 10000000})
  const laRef = firestore.get({collection: 'cities', doc: 'LA'})
  firestore.delete(laRef)
  const runBatch = async () => await batch.commit()

  return <button onClick={runBatch}>Attempt Batch</button>
}
Alex Mckay
  • 3,463
  • 16
  • 27
  • `const firestore = useFirestore(); const batch = firestore.batch();` unfortunately I get the typescript error => Property 'batch' does not exist on type 'ExtendedFirestoreInstance'. Any Ideas? – F.Fabian Aug 22 '22 at 10:03
  • 1
    You can see that the method is added [here](https://github.com/prescottprue/redux-firestore/blob/80509370c681c2bd848f7185aec30d0d0d28fe50/src/constants.js#L134) and [here](https://github.com/prescottprue/redux-firestore/blob/80509370c681c2bd848f7185aec30d0d0d28fe50/src/createFirestoreInstance.js#L43). Try adding a `@ts-expect-error` above `const batch = firestore.batch()` and see if the Javascript works. I have had it working before so I know it is possible. I am just unable to check how at the moment. – Alex Mckay Aug 24 '22 at 22:15