Skip to content

Announcing the Capacitor Firebase Cloud Firestore Plugin

Today we are excited to announce the release of the Capacitor Firebase Cloud Firestore plugin, sponsored by AppScreens. This plugin allows you to use the Android and iOS SDKs for Firebase Cloud Firestore in your Capacitor project.

Until now, it was necessary to use the Firebase JavaScript SDK on Android and iOS as well to use Cloud Firestore. However, this had some drawbacks, such as the need for additional authentication of users in the web layer and degraded performance. The Capacitor Firebase Cloud Firestore plugin addresses these drawbacks by providing a native implementation for Android and iOS.

Demo

Demo

Let's take a quick look at the Capacitor Firebase Cloud Firestore API and how you can add, get and delete data from your database.

Installation

Run the following commands to install the plugin:

npm install @capacitor-firebase/firestore
npx cap sync

You also need to add Firebase to your project if you haven't already.

Usage

If you are new to Cloud Firestore, we recommend that you first read the Understand Cloud Firestore section so that you are familiar with the basics. Let's see the plugin in action.

Add data

There are several ways to write data to Cloud Firestore. One way is to add a new document to a collection with an automatically generated document identifier using the addDocument(...) method:

import { FirebaseFirestore } from '@capacitor-firebase/firestore';

const addDocument = async () => {
  const { reference } = await FirebaseFirestore.addDocument({
    reference: 'users',
    data: { 
      first: 'Alan', 
      last: 'Turing', 
      born: 1912 
    },
  });
  return reference.id;
};

In this case we add a new document with the data { first: 'Alan', last: 'Turing', born: 1912 } to the collection users.

Another way is to set the content of a document within a collection by explicitly specifying a document identifier using the setDocument(...) method:

import { FirebaseFirestore } from '@capacitor-firebase/firestore';

const setDocument = async () => {
  await FirebaseFirestore.setDocument({
    reference: 'users/Aorq09lkt1ynbR7xhTUx',
    data: { 
      first: 'Alan', 
      last: 'Turing', 
      born: 1912 
    },
    merge: true,
  });
};

Use { merge: boolean } to specify whether the newly provided data should overwrite the content of the document or be merged with the existing document.

Get data

To retrieve a single document from a collection, you can use the getDocument(...) method:

import { FirebaseFirestore } from '@capacitor-firebase/firestore';

const getDocument = async () => {
  const { snapshot } = await FirebaseFirestore.getDocument({
    reference: 'users/Aorq09lkt1ynbR7xhTUx',
  });
  return snapshot;
};

You just need to pass the document reference as a string, with path components separated by a forward slash (/).

To retrieve multiple documents from a collection, you can use the getCollection(...) method:

import { FirebaseFirestore } from '@capacitor-firebase/firestore';

const getCollection = async () => {
  const { snapshots } = await FirebaseFirestore.getCollection({
    reference: 'users',
    compositeFilter: {
      type: 'and',
      queryConstraints: [
        {
          type: 'where',
          fieldPath: 'born',
          opStr: '==',
          value: 1912,
        },
      ],
    },
    queryConstraints: [
      {
        type: 'orderBy',
        fieldPath: 'born',
        directionStr: 'desc',
      },
      {
        type: 'limit',
        limit: 10,
      },
    ],
  });
  return snapshots;
};

This method allows you to apply filters and sorting to the query. It is recommended that you specify the type property first, so that TypeScript will list the remaining properties for you.

Delete data

To delete a document from a collection, you can use the deleteDocument(...) method:

import { FirebaseFirestore } from '@capacitor-firebase/firestore';

const deleteDocument = async () => {
  await FirebaseFirestore.deleteDocument({
    reference: 'users/Aorq09lkt1ynbR7xhTUx',
  });
};

Again you just need to pass the document reference as a string, with path components separated by a forward slash (/).

Get real-time updates

If you want to get real-time updates when documents change, you can use the addDocumentSnapshotListener(...) and addCollectionSnapshotListener(...) methods:

import { FirebaseFirestore } from '@capacitor-firebase/firestore';


const addDocumentSnapshotListener = async () => {
  const callbackId = await FirebaseFirestore.addDocumentSnapshotListener(
    {
      reference: 'users/Aorq09lkt1ynbR7xhTUx',
    },
    (event, error) => {
      if (error) {
        console.error(error);
      } else {
        console.log(event);
      }
    }
  );
  return callbackId;
};

const addCollectionSnapshotListener = async () => {
  const callbackId = await FirebaseFirestore.addCollectionSnapshotListener(
    {
      reference: 'users',
    },
    (event, error) => {
      if (error) {
        console.error(error);
      } else {
        console.log(event);
      }
    }
  );
  return callbackId;
};

The callback function will be called every time the document or collection changes. To remove the listener, you have to call the removeSnapshotListener(...) or removeAllListeners() methods:

import { FirebaseFirestore } from '@capacitor-firebase/firestore';

const removeSnapshotListener = async (callbackId: string) => {
  await FirebaseFirestore.removeSnapshotListener({
    callbackId,
  });
};

const removeAllListeners = async () => {
  await FirebaseFirestore.removeAllListeners();
};

Limitations

Currently, there are still a few limitations that you need to be aware of:

  1. Data types: The supported data types are those that can be represented in JSON such as numbers, strings, booleans, arrays, and objects. Something that is not currently supported is, for example, the JavaScript Date object. However, you can just pass the Date as a string by using the toISOString() method:
    // Create a string representation of the current date based on ISO 8601
    const dateString = new Date().toISOString();
    // Create a new date object from the string
    const date = new Date(dateString);
    
  2. Field values: Firestore supports various field values such as FieldValue.delete(), FieldValue.increment() or FieldValue.serverTimestamp(). However, these will not be supported until the next release (see capacitor-firebase/issues/443).

Closing Thoughts

Be sure to check out our API Reference to see what else you can do with this plugin. Also feel free to check out our base sponsor AppScreens - a dedicated screenshot mockup generator for app developers.