mirror of
https://github.com/zhigang1992/react-native-firebase.git
synced 2026-01-12 22:50:20 +08:00
chore(docs): prettier & gen new typedocs
This commit is contained in:
@@ -20,9 +20,7 @@ Google AdMob dashboard under "Ad units" should be used:
|
||||
```js
|
||||
import { InterstitialAd, TestIds } from '@react-native-firebase/admob';
|
||||
|
||||
const adUnitId = __DEV__
|
||||
? TestIds.INTERSTITIAL
|
||||
: 'ca-app-pub-xxxxxxxxxxxxx/yyyyyyyyyyyyyy';
|
||||
const adUnitId = __DEV__ ? TestIds.INTERSTITIAL : 'ca-app-pub-xxxxxxxxxxxxx/yyyyyyyyyyyyyy';
|
||||
|
||||
const interstitial = InterstitialAd.createForAdRequest(adUnitId, {
|
||||
requestNonPersonalizedAdsOnly: true,
|
||||
@@ -43,15 +41,9 @@ To listen to events, such as when the advert from the network has loaded or when
|
||||
```jsx
|
||||
import React, { useEffect, useState } from 'react';
|
||||
import { Button } from 'react-native';
|
||||
import {
|
||||
InterstitialAd,
|
||||
AdEventType,
|
||||
TestIds,
|
||||
} from '@react-native-firebase/admob';
|
||||
import { InterstitialAd, AdEventType, TestIds } from '@react-native-firebase/admob';
|
||||
|
||||
const adUnitId = __DEV__
|
||||
? TestIds.INTERSTITIAL
|
||||
: 'ca-app-pub-xxxxxxxxxxxxx/yyyyyyyyyyyyyy';
|
||||
const adUnitId = __DEV__ ? TestIds.INTERSTITIAL : 'ca-app-pub-xxxxxxxxxxxxx/yyyyyyyyyyyyyy';
|
||||
|
||||
const interstitial = InterstitialAd.createForAdRequest(adUnitId, {
|
||||
requestNonPersonalizedAdsOnly: true,
|
||||
@@ -120,9 +112,7 @@ Google AdMob dashboard under "Ad units" should be used:
|
||||
```js
|
||||
import { RewardedAd, TestIds } from '@react-native-firebase/admob';
|
||||
|
||||
const adUnitId = __DEV__
|
||||
? TestIds.INTERSTITIAL
|
||||
: 'ca-app-pub-xxxxxxxxxxxxx/yyyyyyyyyyyyyy';
|
||||
const adUnitId = __DEV__ ? TestIds.INTERSTITIAL : 'ca-app-pub-xxxxxxxxxxxxx/yyyyyyyyyyyyyy';
|
||||
|
||||
const rewarded = RewardedAd.createForAdRequest(adUnitId, {
|
||||
requestNonPersonalizedAdsOnly: true,
|
||||
@@ -143,15 +133,9 @@ To listen to events, such as when the advert from the network has loaded or when
|
||||
```js
|
||||
import React, { useEffect, useState } from 'react';
|
||||
import { Button } from 'react-native';
|
||||
import {
|
||||
RewardedAd,
|
||||
RewardedAdEventType,
|
||||
TestIds,
|
||||
} from '@react-native-firebase/admob';
|
||||
import { RewardedAd, RewardedAdEventType, TestIds } from '@react-native-firebase/admob';
|
||||
|
||||
const adUnitId = __DEV__
|
||||
? TestIds.REWARDED
|
||||
: 'ca-app-pub-xxxxxxxxxxxxx/yyyyyyyyyyyyyy';
|
||||
const adUnitId = __DEV__ ? TestIds.REWARDED : 'ca-app-pub-xxxxxxxxxxxxx/yyyyyyyyyyyyyy';
|
||||
|
||||
const rewarded = RewardedAd.createForAdRequest(adUnitId, {
|
||||
requestNonPersonalizedAdsOnly: true,
|
||||
@@ -224,9 +208,7 @@ a banner:
|
||||
import React from 'react';
|
||||
import { BannerAd, BannerAdSize, TestIds } from '@react-native-firebase/admob';
|
||||
|
||||
const adUnitId = __DEV__
|
||||
? TestIds.BANNER
|
||||
: 'ca-app-pub-xxxxxxxxxxxxx/yyyyyyyyyyyyyy';
|
||||
const adUnitId = __DEV__ ? TestIds.BANNER : 'ca-app-pub-xxxxxxxxxxxxx/yyyyyyyyyyyyyy';
|
||||
|
||||
function App() {
|
||||
return (
|
||||
|
||||
@@ -76,9 +76,7 @@ To request consent, call the method as early as possible within your app before
|
||||
```js
|
||||
import { AdsConsent } from '@react-native-firebase/admob';
|
||||
|
||||
const consentInfo = await AdsConsent.requestInfoUpdate([
|
||||
'pub-6189033257628123',
|
||||
]);
|
||||
const consentInfo = await AdsConsent.requestInfoUpdate(['pub-6189033257628123']);
|
||||
```
|
||||
|
||||
The result of the method returns an `AdsConsentInfo` interface, which provides information about the users status and location:
|
||||
@@ -130,9 +128,7 @@ You must provide a privacy policy URL.
|
||||
```js
|
||||
import { AdsConsent, AdsConsentStatus } from '@react-native-firebase/admob';
|
||||
|
||||
const consentInfo = await AdsConsent.requestInfoUpdate([
|
||||
'pub-6189033257628123',
|
||||
]);
|
||||
const consentInfo = await AdsConsent.requestInfoUpdate(['pub-6189033257628123']);
|
||||
|
||||
if (
|
||||
consentInfo.isRequestLocationInEeaOrUnknown &&
|
||||
@@ -220,10 +216,7 @@ To set a debug location, use the `setDebugGeography` method. It accepts 3 values
|
||||
For example:
|
||||
|
||||
```js
|
||||
import {
|
||||
AdsConsent,
|
||||
AdsConsentDebugGeography,
|
||||
} from '@react-native-firebase/admob';
|
||||
import { AdsConsent, AdsConsentDebugGeography } from '@react-native-firebase/admob';
|
||||
|
||||
await AdsConsent.setDebugGeography(AdsConsentDebugGeography.EEA);
|
||||
```
|
||||
|
||||
@@ -89,7 +89,7 @@ npx react-native run-android
|
||||
## Configure outbound requests
|
||||
|
||||
Before requesting ads, you must tell the AdMob network what type of content you'd wish to receive based on your target
|
||||
audience.
|
||||
audience.
|
||||
|
||||
For example, if the application targets children then you must configure the outbound requests to only
|
||||
receive content suitable for children before loading any adverts.
|
||||
|
||||
@@ -70,8 +70,8 @@ function App() {
|
||||
|
||||
## Pre-defined Events
|
||||
|
||||
To help you get started, Analytics provides a number of [event methods](/reference/analytics) that are common among
|
||||
different types of apps, including retail and ecommerce, travel, and gaming apps. To learn more about these events and
|
||||
To help you get started, Analytics provides a number of [event methods](/reference/analytics) that are common among
|
||||
different types of apps, including retail and ecommerce, travel, and gaming apps. To learn more about these events and
|
||||
when to use them, browse the [Events and properties](https://support.google.com/analytics/answer/9322688?hl=en&ref_topic=9267641)
|
||||
articles in the Firebase Help Center.
|
||||
|
||||
|
||||
@@ -5,7 +5,7 @@ next: /crashlytics/usage
|
||||
previous: /app/usage
|
||||
---
|
||||
|
||||
The App module also provides access to some handy utility methods which have been exposed to aid with your
|
||||
The App module also provides access to some handy utility methods which have been exposed to aid with your
|
||||
development.
|
||||
|
||||
# File Paths
|
||||
@@ -31,13 +31,13 @@ and screenshots—in the Firebase console.
|
||||
|
||||
It is useful to change the apps configuration if it is being run in Test Lab, for example disabling Analytics
|
||||
data collection. Such functionality can be carried out by taking advantage of the `isRunningInTestLab`.
|
||||
|
||||
|
||||
> Be aware, `isRunningInTestLab` is Android only property!
|
||||
|
||||
```js
|
||||
import { utils } from '@react-native-firebase/app';
|
||||
import analytics from '@react-native-firebase/analytics';
|
||||
|
||||
|
||||
async function bootstrap() {
|
||||
if (utils().isRunningInTestLab) {
|
||||
await analytics().setAnalyticsCollectionEnabled(false);
|
||||
|
||||
@@ -15,7 +15,7 @@ end-user consent prior to using the Firebase Authentication phone number sign-in
|
||||
|
||||
> Firebase Phone Auth is not supported in all countries. Please see their [FAQs](https://firebase.google.com/support/faq/#develop) for more information.
|
||||
|
||||
Ensure the "Phone" sign-in provider is enabled on the [Firebase Console](https://console.firebase.google.com/project/_/authentication/providers).
|
||||
Ensure the "Phone" sign-in provider is enabled on the [Firebase Console](https://console.firebase.google.com/project/_/authentication/providers).
|
||||
|
||||
# Sign-in
|
||||
|
||||
@@ -62,10 +62,7 @@ function PhoneSignIn() {
|
||||
return (
|
||||
<>
|
||||
<TextInput value={code} onChangeText={text => setCode(text)} />
|
||||
<Button
|
||||
title="Confirm Code"
|
||||
onPress={() => confirmCode()}
|
||||
/>
|
||||
<Button title="Confirm Code" onPress={() => confirmCode()} />
|
||||
</>
|
||||
);
|
||||
}
|
||||
@@ -85,5 +82,5 @@ On the [Firebase Console](https://console.firebase.google.com/project/_/authenti
|
||||
|
||||
Enter a new phone number (e.g. `+44 7444 555666`) and a test code (e.g. `123456`).
|
||||
|
||||
Once added, the number can be used with the `signInWithPhoneNumber` method, and entering the code specified will
|
||||
cause a successful sign-in.
|
||||
Once added, the number can be used with the `signInWithPhoneNumber` method, and entering the code specified will
|
||||
cause a successful sign-in.
|
||||
|
||||
@@ -5,7 +5,7 @@ next: /auth/phone-auth
|
||||
previous: /auth/usage
|
||||
---
|
||||
|
||||
React Native Firebase provides support for integrating with different social platforms. The authentication with these
|
||||
React Native Firebase provides support for integrating with different social platforms. The authentication with these
|
||||
different platforms is left to the developer to implement due to the various implementations and flows possible using
|
||||
their oAuth APIs.
|
||||
|
||||
@@ -21,10 +21,10 @@ To integrate Apple Sign-In on your iOS applications, you need to install a 3rd p
|
||||
Once authentication is successful, a Firebase credential can be used to sign the user into Firebase with their Apple account.
|
||||
|
||||
To get started, you must first install the [`react-native-apple-authentication`](https://github.com/invertase/react-native-apple-authentication)
|
||||
library. There are a number of [prerequisites](https://github.com/invertase/react-native-apple-authentication#prerequisites-to-using-this-library) to using the library, including
|
||||
library. There are a number of [prerequisites](https://github.com/invertase/react-native-apple-authentication#prerequisites-to-using-this-library) to using the library, including
|
||||
[setting up your Apple Developer account](https://github.com/invertase/react-native-apple-authentication/blob/master/docs/INITIAL_SETUP.md) to enable Apple Sign-In.
|
||||
|
||||
Ensure the "Apple" sign-in provider is enabled on the [Firebase Console](https://console.firebase.google.com/project/_/authentication/providers).
|
||||
Ensure the "Apple" sign-in provider is enabled on the [Firebase Console](https://console.firebase.google.com/project/_/authentication/providers).
|
||||
|
||||
Once setup, we can trigger an initial request to allow user to sign in with their Apple account, using a pre-rendered
|
||||
button the `react-native-apple-authentication` library provides:
|
||||
@@ -55,8 +55,8 @@ passing in the scope required for our application:
|
||||
import auth from '@react-native-firebase/auth';
|
||||
import appleAuth, {
|
||||
AppleAuthRequestScope,
|
||||
AppleAuthRequestOperation
|
||||
} from '@invertase/react-native-apple-authentication';
|
||||
AppleAuthRequestOperation,
|
||||
} from '@invertase/react-native-apple-authentication';
|
||||
|
||||
async function onAppleButtonPress() {
|
||||
// Start the sign-in request
|
||||
@@ -64,14 +64,14 @@ async function onAppleButtonPress() {
|
||||
requestedOperation: AppleAuthRequestOperation.LOGIN,
|
||||
requestedScopes: [AppleAuthRequestScope.EMAIL, AppleAuthRequestScope.FULL_NAME],
|
||||
});
|
||||
|
||||
|
||||
// Ensure Apple returned a user identityToken
|
||||
if (!appleAuthRequestResponse.identityToken) {
|
||||
throw 'Apple Sign-In failed - no identify token returned';
|
||||
}
|
||||
|
||||
// Create a Firebase credential from the response
|
||||
const { identityToken, nonce } = appleAuthRequestResponse;
|
||||
const { identityToken, nonce } = appleAuthRequestResponse;
|
||||
const appleCredential = auth.AppleAuthProvider.credential(identityToken, nonce);
|
||||
|
||||
// Sign the user in with the credential
|
||||
@@ -89,9 +89,9 @@ the native Facebook SDKs to enable Facebook sign-in.
|
||||
|
||||
Before getting started, ensure you have installed the library, [configured your Android & iOS applications](https://developers.facebook.com/docs/android/getting-started/) and
|
||||
setup your [Facebook Developer Account](https://github.com/facebook/react-native-fbsdk#3-configure-projects)
|
||||
to enable Facebook Login.
|
||||
to enable Facebook Login.
|
||||
|
||||
Ensure the "Facebook" sign-in provider is enabled on the [Firebase Console](https://console.firebase.google.com/project/_/authentication/providers).
|
||||
Ensure the "Facebook" sign-in provider is enabled on the [Firebase Console](https://console.firebase.google.com/project/_/authentication/providers).
|
||||
|
||||
Once setup, we can trigger the login flow with Facebook by calling the `logInWithPermissions` method on the `LoginManager`
|
||||
class:
|
||||
@@ -123,14 +123,14 @@ async function onFacebookButtonPress() {
|
||||
if (result.isCancelled) {
|
||||
throw 'User cancelled the login process';
|
||||
}
|
||||
|
||||
|
||||
// Once signed in, get the users AccesToken
|
||||
const data = await AccessToken.getCurrentAccessToken();
|
||||
|
||||
if (!data) {
|
||||
throw 'Something went wrong obtaining access token';
|
||||
}
|
||||
|
||||
|
||||
// Create a Firebase credential with the AccessToken
|
||||
const facebookCredential = auth.FacebookAuthProvider.credential(data.accessToken);
|
||||
|
||||
@@ -149,17 +149,17 @@ we can sign-in the user with Twitter and generate a credential which can be used
|
||||
|
||||
To get started, install the library and ensure you have completed setup, following the required [prerequisites](https://github.com/GoldenOwlAsia/react-native-twitter-signin#prerequisites) list.
|
||||
|
||||
Ensure the "Twitter" sign-in provider is enabled on the [Firebase Console](https://console.firebase.google.com/project/_/authentication/providers).
|
||||
Ensure the "Twitter" sign-in provider is enabled on the [Firebase Console](https://console.firebase.google.com/project/_/authentication/providers).
|
||||
|
||||
Before triggering a sign-in request, you must initialize the Twitter SDK using your accounts consumer key & secret:
|
||||
|
||||
```js
|
||||
import { NativeModules } from 'react-native';
|
||||
const { RNTwitterSignIn } = NativeModules;
|
||||
|
||||
RNTwitterSignIn
|
||||
.init('TWITTER_CONSUMER_KEY', 'TWITTER_CONSUMER_SECRET')
|
||||
.then(() => console.log('Twitter SDK initialized'));
|
||||
|
||||
RNTwitterSignIn.init('TWITTER_CONSUMER_KEY', 'TWITTER_CONSUMER_SECRET').then(() =>
|
||||
console.log('Twitter SDK initialized'),
|
||||
);
|
||||
```
|
||||
|
||||
Once initalized, setup your application to trigger a sign-in request with Twitter using the `login` method.
|
||||
@@ -209,7 +209,7 @@ Most configuration is already setup when using Google Sign-In with Firebase, how
|
||||
SHA1 key has been configured for use with Android. You can see view how to generate the key on the [Getting Started](/)
|
||||
documentation.
|
||||
|
||||
Ensure the "Google" sign-in provider is enabled on the [Firebase Console](https://console.firebase.google.com/project/_/authentication/providers).
|
||||
Ensure the "Google" sign-in provider is enabled on the [Firebase Console](https://console.firebase.google.com/project/_/authentication/providers).
|
||||
|
||||
Before triggering a sign-in request, you must initialize the Google SDK using your any required scopes and the
|
||||
`webClientId`, which can be found on the Firebase Console Settings, as "Web API Key".
|
||||
|
||||
@@ -8,7 +8,7 @@ previous: /analytics/screen-tracking
|
||||
|
||||
# Installation
|
||||
|
||||
This module requires that the `@react-native-firebase/app` module is already setup and installed. To install the "app"
|
||||
This module requires that the `@react-native-firebase/app` module is already setup and installed. To install the "app"
|
||||
module, view the [Getting Started](/) documentation.
|
||||
|
||||
```bash
|
||||
@@ -27,12 +27,12 @@ you can follow the manual installation steps for [iOS](/auth/usage/installation/
|
||||
|
||||
# What does it do
|
||||
|
||||
Firebase Authentication provides backend services & easy-to-use SDKs to authenticate users to your app. It supports
|
||||
Firebase Authentication provides backend services & easy-to-use SDKs to authenticate users to your app. It supports
|
||||
authentication using passwords, phone numbers, popular federated identity providers like Google, Facebook and Twitter, and more.
|
||||
|
||||
<Youtube id="8sGY55yxicA" />
|
||||
|
||||
Firebase Authentication integrates tightly with other Firebase services, and it leverages industry standards like OAuth
|
||||
Firebase Authentication integrates tightly with other Firebase services, and it leverages industry standards like OAuth
|
||||
2.0 and OpenID Connect, so it can be easily integrated with your custom backend.
|
||||
|
||||
# Usage
|
||||
@@ -51,25 +51,25 @@ render of our main application whilst the connection is established:
|
||||
import React, { useState, useEffect } from 'react';
|
||||
import { View, Text } from 'react-native';
|
||||
import auth from '@react-native-firebase/auth';
|
||||
|
||||
|
||||
function App() {
|
||||
// Set an initializing state whilst Firebase connects
|
||||
const [initializing, setInitializing] = useState(true);
|
||||
const [user, setUser] = useState();
|
||||
|
||||
|
||||
// Handle user state changes
|
||||
function onAuthStateChanged(user) {
|
||||
setUser(user);
|
||||
if (initializing) setInitializing(false);
|
||||
}
|
||||
|
||||
|
||||
useEffect(() => {
|
||||
const subscriber = auth().onAuthStateChanged(onAuthStateChanged);
|
||||
return subscriber; // unsubscribe on unmount
|
||||
}, []);
|
||||
|
||||
|
||||
if (initializing) return null;
|
||||
|
||||
|
||||
if (!user) {
|
||||
return (
|
||||
<View>
|
||||
@@ -77,7 +77,7 @@ function App() {
|
||||
</View>
|
||||
);
|
||||
}
|
||||
|
||||
|
||||
return (
|
||||
<View>
|
||||
<Text>Welcome {user.email}</Text>
|
||||
@@ -86,15 +86,15 @@ function App() {
|
||||
}
|
||||
```
|
||||
|
||||
If the `user` returned within the handler is `null` we assume the user is currently signed-out, otherwise they are
|
||||
signed-in and a [`User`](/reference/auth/user) interface is returned.
|
||||
If the `user` returned within the handler is `null` we assume the user is currently signed-out, otherwise they are
|
||||
signed-in and a [`User`](/reference/auth/user) interface is returned.
|
||||
|
||||
The `onAuthStateChanged` method also returns an unsubscriber function which allows us to stop listening for events whenever
|
||||
the hook is no longer in use.
|
||||
|
||||
## Persisting authentication state
|
||||
|
||||
On web based applications, the Firebase Web SDK takes advantage of features such as cookies and localstorage to persist
|
||||
On web based applications, the Firebase Web SDK takes advantage of features such as cookies and localstorage to persist
|
||||
the users authenticated state across sessions. The native Firebase SDKs also provide this functionality using device native SDKs,
|
||||
ensuring that a users previous authentication state between app sessions is persisted.
|
||||
|
||||
@@ -103,21 +103,21 @@ The user is able to clear their state by deleting the apps data/cache from the d
|
||||
## Anonymous sign-in
|
||||
|
||||
Some applications don't require authentication, which make it tricky to identify what users are doing throughout your app.
|
||||
If connecting with external APIs, it is also useful to add an extra layer of security by ensuring the users request is
|
||||
If connecting with external APIs, it is also useful to add an extra layer of security by ensuring the users request is
|
||||
from the app. This can be achieved with the `signInAnonymously` method, which creates a new anonymous user which is persisted,
|
||||
allowing you to integrate with other services such as Analytics by providing a user ID.
|
||||
|
||||
Ensure the "Anonymous" sign-in provider is enabled on the [Firebase Console](https://console.firebase.google.com/project/_/authentication/providers).
|
||||
Ensure the "Anonymous" sign-in provider is enabled on the [Firebase Console](https://console.firebase.google.com/project/_/authentication/providers).
|
||||
|
||||
```js
|
||||
import auth from '@react-native-firebase/auth';
|
||||
|
||||
|
||||
auth()
|
||||
.signInAnonymously()
|
||||
.then(() => {
|
||||
console.log('User signed in anonymously');
|
||||
})
|
||||
.catch((error) => {
|
||||
.catch(error => {
|
||||
if (error.code === 'auth/operation-not-allowed') {
|
||||
console.log('Enable anonymous in your firebase console.');
|
||||
}
|
||||
@@ -134,28 +134,28 @@ to the error. For a full list of error codes available, view the [Firebase docum
|
||||
|
||||
## Email/Password sign-in
|
||||
|
||||
Email/password sign in is a common method for user sign in on applications. This requires the user to provide an email
|
||||
address and secure password. Users can both register and sign in using a method called `createUserWithEmailAndPassword`
|
||||
Email/password sign in is a common method for user sign in on applications. This requires the user to provide an email
|
||||
address and secure password. Users can both register and sign in using a method called `createUserWithEmailAndPassword`
|
||||
or sign in to an existing account with `signInWithEmailAndPassword`.
|
||||
|
||||
Ensure the "Email/Password" sign-in provider is enabled on the [Firebase Console](https://console.firebase.google.com/project/_/authentication/providers).
|
||||
Ensure the "Email/Password" sign-in provider is enabled on the [Firebase Console](https://console.firebase.google.com/project/_/authentication/providers).
|
||||
|
||||
The `createUserWithEmailAndPassword` performs to operations; first creating the user if they do not already exist, and
|
||||
The `createUserWithEmailAndPassword` performs to operations; first creating the user if they do not already exist, and
|
||||
then signing them in.
|
||||
|
||||
```js
|
||||
import auth from '@react-native-firebase/auth';
|
||||
|
||||
|
||||
auth()
|
||||
.createUserWithEmailAndPassword('sarah.lane@gmail.com', 'SuperSecretPassword!')
|
||||
.then(() => {
|
||||
console.log('User account created & signed in!');
|
||||
})
|
||||
.catch((error) => {
|
||||
.catch(error => {
|
||||
if (error.code === 'auth/email-already-in-use') {
|
||||
console.log('That email address is already in use!');
|
||||
}
|
||||
|
||||
|
||||
if (error.code === 'auth/invalid-email') {
|
||||
console.log('That email address is invalid!');
|
||||
}
|
||||
|
||||
@@ -6,12 +6,11 @@ previous: /releases
|
||||
---
|
||||
|
||||
Firstly, thanks for considering contributing to React Native Firebase! It's people like you that make the open source
|
||||
community such a great community!Firstly, thanks for considering contributing to React Native Firebase! It's people
|
||||
community such a great community! Firstly, thanks for considering contributing to React Native Firebase! It's people
|
||||
like you that make the open source community such a great community!
|
||||
|
||||
We welcome any type of contribution, not just code. You can learn more about the various ways of contributing to this
|
||||
project by visiting any of the sections below.
|
||||
|
||||
|
||||
# Issues & PRs
|
||||
|
||||
@@ -35,10 +34,10 @@ Here are some example review checks that can be taken on issues;
|
||||
|
||||
# Documentation
|
||||
|
||||
All documentation is open sourced and we are happy to accept contributions whether they are typo fixes or new pages.
|
||||
All documentation is open sourced and we are happy to accept contributions whether they are typo fixes or new pages.
|
||||
Content is written in Markdown, and takes advantage of [MDX](https://github.com/mdx-js/mdx) to provide powerful functionality on-top of Markdown.
|
||||
|
||||
Our documentation reference is automatically generated from each packages TypeScript declaration. Our build process
|
||||
Our documentation reference is automatically generated from each packages TypeScript declaration. Our build process
|
||||
automatically generates a `typedoc.json` file using Typedoc, which is then parsed into a consumable format for our documentation generator.
|
||||
|
||||
# Community
|
||||
@@ -47,6 +46,7 @@ We always love to hear about React Native Firebase being featured at community e
|
||||
or attending an event which involves the library, please let us know using the form below.
|
||||
|
||||
We'd love to help promote the event via:
|
||||
|
||||
- Twitter exposure on our [@rnfirebase](https://twitter.com/rnfirebase) account.
|
||||
- Members of our team attending the event in person.
|
||||
- Giving out React Native Firebase T-Shirts.
|
||||
|
||||
@@ -8,9 +8,9 @@ description: Additional Android steps for Crashlytics integration
|
||||
# Adding Fabric Gradle Tools
|
||||
|
||||
These steps are required, if you do not add these your app will most likely crash at startup with the following Error:
|
||||
|
||||
|
||||
"The Crashlytics build ID is missing. This occurs when Crashlytics tooling is absent from your app's build configuration.
|
||||
Please review Crashlytics onboarding instructions and ensure you have a valid Crashlytics account."_
|
||||
Please review Crashlytics onboarding instructions and ensure you have a valid Crashlytics account."\_
|
||||
|
||||
## 1. Add the Fabric Maven repository
|
||||
|
||||
@@ -56,9 +56,9 @@ apply plugin: 'io.fabric'
|
||||
// ..
|
||||
```
|
||||
|
||||
## 4. (Optional) Enable Crashlytics NDK reporting
|
||||
## 4. (Optional) Enable Crashlytics NDK reporting
|
||||
|
||||
Crashlytics NDK reporting allows you to capture Native Development Kit crashes, e.g. in React Native this will capture
|
||||
Crashlytics NDK reporting allows you to capture Native Development Kit crashes, e.g. in React Native this will capture
|
||||
crashes originating from the Yoga layout engine.
|
||||
|
||||
Add the `crashlytics` block line to the `android/app/build.gradle` file:
|
||||
|
||||
@@ -7,8 +7,8 @@ previous: /crashlytics/usage
|
||||
|
||||
# Overview
|
||||
|
||||
Once you have Crashlytics up and running in your app, you can navigate to Crashlytics in your Firebase Console underneath
|
||||
'Quality' and start reviewing the reports as they come in. If this page still tells you to setup, build or run your app
|
||||
Once you have Crashlytics up and running in your app, you can navigate to Crashlytics in your Firebase Console underneath
|
||||
'Quality' and start reviewing the reports as they come in. If this page still tells you to setup, build or run your app
|
||||
then you have not correctly setup Crashlytics in your app (see [Usage](/crashlytics/usage)).
|
||||
|
||||
> Keep in mind when testing out Crashlytics that Crashlytics is [disabled by default in debug mode](crashlytics/usage#crashlytics-in-debug-mode).
|
||||
@@ -21,9 +21,9 @@ In this example the [Crash Attributes](crashlytics/usage#crash-attributes) examp
|
||||
|
||||
## Issues
|
||||
|
||||
Under issues, Firebase has gathered all the reports from your app and organised them into separate issues, where each
|
||||
Under issues, Firebase has gathered all the reports from your app and organised them into separate issues, where each
|
||||
issue is an unique crash or stack trace in your app. One of the issues visible in the example shown originates from `CrashTest.java`,
|
||||
which is the Android module responsible for testing Crashlytics through the `crash` method, throwing an uncaught exception
|
||||
which is the Android module responsible for testing Crashlytics through the `crash` method, throwing an uncaught exception
|
||||
to crash the app. Using this method on the same platform will always add reports to the same issue.
|
||||
|
||||
# Managing issues
|
||||
@@ -42,7 +42,7 @@ about the associated user. Under keys you can see the custom attributes that we
|
||||
## Closing issues
|
||||
|
||||
Note that in the top right there is a button that says 'Close'. After having addressed an issue you can close it, allowing
|
||||
you to filter it out in the overview by selecting 'Open' under 'Issue state', when clicking on the 'Filter issues' button.
|
||||
you to filter it out in the overview by selecting 'Open' under 'Issue state', when clicking on the 'Filter issues' button.
|
||||
This is visible in the first example, where we're displaying only 3 relevant non-fatal events out of the 12 that occured.
|
||||
When the same issue re-occurs, it will automatically open again. By clicking the arrow next to the button we can mute the
|
||||
issue, preventing this from happening.
|
||||
|
||||
@@ -48,7 +48,7 @@ Use the `log` method throughout your app to accumulate extra context for possibl
|
||||
|
||||
Crashlytics also supports sending JavaScript stack traces to the Firebase console. This can be used in any situation where an error occurs but is caught by your own code to recover gracefully. To send a stack trace, pass a JavaScript Error to the `recordError` method.
|
||||
|
||||
> Crash reporting is disabled by default whilst developing. To enable this, view the [enable debug crash logs](#enable-debug-crash-logs) documentation.
|
||||
> Crash reporting is disabled by default whilst developing. To enable this, view the [enable debug crash logs](#enable-debug-crash-logs) documentation.
|
||||
|
||||
## Crash Attributes
|
||||
|
||||
@@ -135,9 +135,7 @@ export default function App() {
|
||||
if (userCounts) {
|
||||
return (
|
||||
<View>
|
||||
<Text>
|
||||
There are currently {userCounts[userCounts.length - 1]} users.
|
||||
</Text>
|
||||
<Text>There are currently {userCounts[userCounts.length - 1]} users.</Text>
|
||||
</View>
|
||||
);
|
||||
}
|
||||
@@ -161,9 +159,7 @@ import { View, Button } from 'react-native';
|
||||
import crashlytics from '@react-native-firebase/crashlytics';
|
||||
|
||||
function App() {
|
||||
const [enabled, setEnabled] = useState(
|
||||
crashlytics().isCrashlyticsCollectionEnabled
|
||||
);
|
||||
const [enabled, setEnabled] = useState(crashlytics().isCrashlyticsCollectionEnabled);
|
||||
|
||||
async function toggleCrashlytics() {
|
||||
await crashlytics()
|
||||
@@ -185,7 +181,7 @@ function App() {
|
||||
|
||||
## Disable Auto Collection
|
||||
|
||||
Additionally, you can configure whether Crashlytics sends out any reports through the `auto_collection_enabled` option in
|
||||
Additionally, you can configure whether Crashlytics sends out any reports through the `auto_collection_enabled` option in
|
||||
your `firebase.json` config. If you want users to opt-in, it is recommended that you disable this here and enable it later
|
||||
through the method once they opt-in.
|
||||
|
||||
@@ -213,8 +209,8 @@ Because you have stack traces readily available while you're debugging your app,
|
||||
|
||||
## Crashlytics NDK
|
||||
|
||||
React Native Firebase supports [Crashlytics NDK](https://docs.fabric.io/android/crashlytics/ndk.html#using-gradle) reporting
|
||||
which is enabled by default. This allows Crashlytics to capture crashes originating from the Yoga layout engine used by
|
||||
React Native Firebase supports [Crashlytics NDK](https://docs.fabric.io/android/crashlytics/ndk.html#using-gradle) reporting
|
||||
which is enabled by default. This allows Crashlytics to capture crashes originating from the Yoga layout engine used by
|
||||
React Native. You can disable Crashlytics NDK in your `firebase.json` config.
|
||||
|
||||
```json
|
||||
|
||||
@@ -24,7 +24,7 @@ database()
|
||||
.then(() => console.log('Realtime Database persistence enabled'));
|
||||
|
||||
AppRegistry.registerComponent('app', () => App);
|
||||
```
|
||||
```
|
||||
|
||||
# Going offline
|
||||
|
||||
@@ -45,12 +45,12 @@ import database from '@react-native-firebase/database';
|
||||
|
||||
function App() {
|
||||
useEffect(() => {
|
||||
const userAgeRef = database().ref('/users/123/age')
|
||||
|
||||
userAgeRef.on('value', (snapshot) => {
|
||||
const userAgeRef = database().ref('/users/123/age');
|
||||
|
||||
userAgeRef.on('value', snapshot => {
|
||||
console.log('Users age: ', snapshot.val());
|
||||
});
|
||||
|
||||
|
||||
database()
|
||||
.goOffline()
|
||||
.then(() => {
|
||||
@@ -59,15 +59,15 @@ function App() {
|
||||
.then(() => {
|
||||
console.log('User updated whilst offline.');
|
||||
});
|
||||
}, [])
|
||||
}, []);
|
||||
}
|
||||
```
|
||||
|
||||
The above code will first execute the `on` listener with data from the remote database.
|
||||
The above code will first execute the `on` listener with data from the remote database.
|
||||
|
||||
Once offline, the `set` method on the reference node will `locally` be set to a new value.
|
||||
Once offline, the `set` method on the reference node will `locally` be set to a new value.
|
||||
|
||||
The `on` listener
|
||||
The `on` listener
|
||||
however will now subscribe to the local database and provide the new value.
|
||||
|
||||
This provides the ability to write code which works in both an online and offline environment without worrying about
|
||||
@@ -86,10 +86,10 @@ await database().goOnline();
|
||||
|
||||
# Local persistence size
|
||||
|
||||
By default Firebase Database will use up to `10MB` of disk space to cache data. If the cache grows beyond this size,
|
||||
By default Firebase Database will use up to `10MB` of disk space to cache data. If the cache grows beyond this size,
|
||||
Firebase Database will start removing data that hasn't been recently used. If you find that your application caches too
|
||||
little or too much data, call the `setPersistenceCacheSizeBytes` method to update the default cache size:
|
||||
|
||||
little or too much data, call the `setPersistenceCacheSizeBytes` method to update the default cache size:
|
||||
|
||||
```js
|
||||
import database from '@react-native-firebase/database';
|
||||
|
||||
|
||||
@@ -14,7 +14,7 @@ and you wish to view which of your users are currently online.
|
||||
|
||||
# Setup
|
||||
|
||||
To get started, we first need a location to store our online users.
|
||||
To get started, we first need a location to store our online users.
|
||||
|
||||
To keep things simple we'll assume the user is authenticated (e.g. with [Firebase Authentication](/auth)) so we can use a unique user ID.
|
||||
|
||||
@@ -32,10 +32,8 @@ function App() {
|
||||
|
||||
const reference = database().ref(`/online/${userId}`);
|
||||
|
||||
// Set the /users/:userId value to true
|
||||
reference
|
||||
.set(true)
|
||||
.then(() => console.log('Online presence set'));
|
||||
// Set the /users/:userId value to true
|
||||
reference.set(true).then(() => console.log('Online presence set'));
|
||||
}, []);
|
||||
}
|
||||
```
|
||||
@@ -53,7 +51,7 @@ Realtime Database API provides a way to execute code on the Firebase servers whe
|
||||
is lost.
|
||||
|
||||
The `onDisconnect` method on a reference returns a new [`OnDisconnect`](/reference/database/ondisconnect) instance. The instance
|
||||
provides functionality to remove or set data whenever a client disconnects. Using the
|
||||
provides functionality to remove or set data whenever a client disconnects. Using the
|
||||
[`remove`](/reference/database/ondisconnect#remove) method we can remove the node on the database if the client disconnects:
|
||||
|
||||
```jsx
|
||||
@@ -68,10 +66,8 @@ function App() {
|
||||
|
||||
const reference = database().ref(`/online/${userId}`);
|
||||
|
||||
// Set the /users/:userId value to true
|
||||
reference
|
||||
.set(true)
|
||||
.then(() => console.log('Online presence set'));
|
||||
// Set the /users/:userId value to true
|
||||
reference.set(true).then(() => console.log('Online presence set'));
|
||||
|
||||
// Remove the node whenever the client disconnects
|
||||
reference
|
||||
|
||||
@@ -27,8 +27,8 @@ you can follow the manual installation steps for [iOS](/database/usage/installat
|
||||
|
||||
# What does it do
|
||||
|
||||
The Realtime Database is a cloud-hosted database. Data is stored as JSON and synchronized in realtime to every connected
|
||||
client. React Native Firebase provides native integration with the Android & iOS Firebase SDKs, supporting both realtime
|
||||
The Realtime Database is a cloud-hosted database. Data is stored as JSON and synchronized in realtime to every connected
|
||||
client. React Native Firebase provides native integration with the Android & iOS Firebase SDKs, supporting both realtime
|
||||
data sync and offline capabilities.
|
||||
|
||||
<Youtube id="U5aeM5dvUpA" />
|
||||
@@ -55,7 +55,7 @@ const reference = database().ref('/users/123');
|
||||
The Realtime Data provides the ability to read the value of a reference as a one-time read, or realtime changes to the node.
|
||||
When a value is read from the database, the API returns a [`DataSnapshot`](/reference/database/datasnapshot).
|
||||
|
||||
The snapshot includes information such as whether the reference node exists, it's value or any children the node has and more.
|
||||
The snapshot includes information such as whether the reference node exists, it's value or any children the node has and more.
|
||||
|
||||
### One-time read
|
||||
|
||||
@@ -67,7 +67,7 @@ import database from '@react-native-firebase/database';
|
||||
database()
|
||||
.ref('/users/123')
|
||||
.once('value')
|
||||
.then((snapshot) => {
|
||||
.then(snapshot => {
|
||||
console.log('User data: ', snapshot.val());
|
||||
});
|
||||
```
|
||||
@@ -81,7 +81,7 @@ import database from '@react-native-firebase/database';
|
||||
|
||||
database()
|
||||
.ref('/users/123')
|
||||
.on('value', (snapshot) => {
|
||||
.on('value', snapshot => {
|
||||
console.log('User data: ', snapshot.val());
|
||||
});
|
||||
```
|
||||
@@ -98,11 +98,10 @@ import database from '@react-native-firebase/database';
|
||||
|
||||
function User({ userId }) {
|
||||
useEffect(() => {
|
||||
const subscriber = database()
|
||||
ref(`/users/${userId}`)
|
||||
.on('value', (snapshot) => {
|
||||
console.log('User data: ', snapshot.val());
|
||||
});
|
||||
const subscriber = database();
|
||||
ref(`/users/${userId}`).on('value', snapshot => {
|
||||
console.log('User data: ', snapshot.val());
|
||||
});
|
||||
|
||||
// Stop listening for updates when no longer required
|
||||
return () => subscriber();
|
||||
@@ -116,7 +115,7 @@ The above example demonstrates how to subscribe to events whenever a value withi
|
||||
may need to only subscribe to events whenever a child node is added/changed/moved/removed. This can be achieved by passing
|
||||
a different [`EventType`](/reference/database/eventtype) to the `on` method.
|
||||
|
||||
If you are listening to a node with many children, only listening to data you care about helps reduce network bandwidth
|
||||
If you are listening to a node with many children, only listening to data you care about helps reduce network bandwidth
|
||||
and speeds up your application.
|
||||
|
||||
```jsx
|
||||
@@ -125,11 +124,10 @@ import database from '@react-native-firebase/database';
|
||||
|
||||
function User({ userId }) {
|
||||
useEffect(() => {
|
||||
const subscriber = database()
|
||||
ref('/users')
|
||||
.on('child_added', (snapshot) => {
|
||||
console.log('A new node has been added', snapshot.val());
|
||||
});
|
||||
const subscriber = database();
|
||||
ref('/users').on('child_added', snapshot => {
|
||||
console.log('A new node has been added', snapshot.val());
|
||||
});
|
||||
|
||||
// Stop listening for updates when no longer required
|
||||
return () => subscriber();
|
||||
@@ -147,7 +145,7 @@ If your application requires more advanced query capabilities, it is recommended
|
||||
#### Ordering
|
||||
|
||||
By default, results are ordered based on the node [keys](#database-keys). If however you are using custom keys you can use
|
||||
one of the `orederByX` methods to order your data.
|
||||
one of the `orederByX` methods to order your data.
|
||||
|
||||
For example, if all of the nodes children are scalar values (string, numbers or booleans) you can use the `orderByValue` method,
|
||||
and Firebase will automatically order the results. The example below would return the `def` node before the `abc` node:
|
||||
@@ -160,9 +158,12 @@ and Firebase will automatically order the results. The example below would retur
|
||||
* 'def': 50,
|
||||
* }
|
||||
* }
|
||||
*/
|
||||
*/
|
||||
|
||||
const scores = database().ref('scores').orderByValue().once('value');
|
||||
const scores = database()
|
||||
.ref('scores')
|
||||
.orderByValue()
|
||||
.once('value');
|
||||
```
|
||||
|
||||
#### Limiting
|
||||
@@ -192,11 +193,11 @@ await database()
|
||||
## Writing data
|
||||
|
||||
The [Firebase documentation](https://firebase.google.com/docs/database/web/structure-data) provides great examples on best
|
||||
practices on how to structure your data. We highly recommend reading the guide before building out your database.
|
||||
practices on how to structure your data. We highly recommend reading the guide before building out your database.
|
||||
|
||||
### Setting data
|
||||
|
||||
The `set` method on a [`Reference`](/reference/database/reference) overwrites all of the existing data at that reference node.
|
||||
The `set` method on a [`Reference`](/reference/database/reference) overwrites all of the existing data at that reference node.
|
||||
The value can be anything; a string, number, object etc:
|
||||
|
||||
```js
|
||||
@@ -238,9 +239,10 @@ sent to remote Firebase database.
|
||||
|
||||
The `push` method will automatically generate a new key if one is not provided:
|
||||
|
||||
|
||||
```js
|
||||
const newReference = database().ref('/users').push()
|
||||
const newReference = database()
|
||||
.ref('/users')
|
||||
.push();
|
||||
|
||||
console.log('Auto generated key: ', newReference.key);
|
||||
|
||||
@@ -252,20 +254,24 @@ newReference
|
||||
```
|
||||
|
||||
The keys generated are ordered to the current time, so the list of items returned from Firebase will be chronologically
|
||||
sorted by default.
|
||||
sorted by default.
|
||||
|
||||
## Removing data
|
||||
|
||||
To remove data, you can call the `remove` method on a reference:
|
||||
|
||||
```js
|
||||
await database().ref('/users/123').remove();
|
||||
await database()
|
||||
.ref('/users/123')
|
||||
.remove();
|
||||
```
|
||||
|
||||
Optionally, you can also set the value of a reference node to `null` to remove it from the database:
|
||||
|
||||
```js
|
||||
await database().ref('/users/123').set(null);
|
||||
await database()
|
||||
.ref('/users/123')
|
||||
.set(null);
|
||||
```
|
||||
|
||||
## Transactions
|
||||
@@ -274,7 +280,7 @@ Transactions are a away to always ensure a write occurs with the latest informat
|
||||
partially apply writes & all writes execute at the end of a successful transaction.
|
||||
|
||||
Imagine a scenario whereby an app has the ability to "Like" user posts. Whenever a user presses the "Like" button,
|
||||
the `/likes/:postId` value (number of likes) on the database increments. Without transactions, we'd first need to
|
||||
the `/likes/:postId` value (number of likes) on the database increments. Without transactions, we'd first need to
|
||||
read the existing value and then increment that value in two separate operations.
|
||||
|
||||
On a high traffic application, the value on the server could already have changed by the time the operation sets a new value,
|
||||
@@ -290,19 +296,18 @@ import database from '@react-native-firebase/database';
|
||||
|
||||
function onPostLike(postId) {
|
||||
const reference = database().ref(`/likes/${postId}`);
|
||||
|
||||
|
||||
// Execute transaction
|
||||
return reference.transaction((currentLikes) => {
|
||||
return reference.transaction(currentLikes => {
|
||||
if (currentLikes === null) return 1;
|
||||
return currentLikes + 1;
|
||||
});
|
||||
}
|
||||
|
||||
// When post "567" is liked
|
||||
onPostLike('567')
|
||||
.then((transaction) => {
|
||||
console.log('New post like count: ', transaction.snapshot.val());
|
||||
});
|
||||
onPostLike('567').then(transaction => {
|
||||
console.log('New post like count: ', transaction.snapshot.val());
|
||||
});
|
||||
```
|
||||
|
||||
Once the transaction is successful, a promise is resolved with a value containing whether the operation committed on the remote
|
||||
@@ -310,7 +315,7 @@ database and the new [`DataSnapshot`](/reference/database/datasnapshot) containi
|
||||
|
||||
# Securing data
|
||||
|
||||
It is important that you understand how to write rules in your firebase console to ensure that your data is secure.
|
||||
It is important that you understand how to write rules in your firebase console to ensure that your data is secure.
|
||||
Please follow the firebase Realtime Database documentation on [security](https://firebase.google.com/docs/database/security)
|
||||
|
||||
# firebase.json
|
||||
|
||||
@@ -31,7 +31,7 @@ Dynamic Links are links that work the way you want, on either iOS or Android and
|
||||
|
||||
<Youtube id="LvY1JMcrPF8" />
|
||||
|
||||
With Dynamic Links, your users get the best available experience for the platform they open your link on. If a user opens
|
||||
With Dynamic Links, your users get the best available experience for the platform they open your link on. If a user opens
|
||||
a Dynamic Link on iOS or Android, they can be taken directly to the linked content in your app.
|
||||
|
||||
# Usage
|
||||
@@ -98,15 +98,14 @@ the application was opened via a link:
|
||||
import dynamicLinks from '@react-native-firebase/dynamic-links';
|
||||
|
||||
function App() {
|
||||
|
||||
useEffect(() => {
|
||||
dynamicLinks()
|
||||
.getInitialLink()
|
||||
.then((link) => {
|
||||
if (link.url === 'https://invertase.io/offer') {
|
||||
// ...set initial route as offers screen
|
||||
}
|
||||
});
|
||||
dynamicLinks()
|
||||
.getInitialLink()
|
||||
.then(link => {
|
||||
if (link.url === 'https://invertase.io/offer') {
|
||||
// ...set initial route as offers screen
|
||||
}
|
||||
});
|
||||
}, []);
|
||||
|
||||
return null;
|
||||
|
||||
@@ -1,9 +1,9 @@
|
||||
---
|
||||
title: Enabling Multidex
|
||||
title: Enabling Multidex
|
||||
description: The Cloud Firestore SDK on Android can sometimes cause Dex errors, learn how to fix them.
|
||||
---
|
||||
|
||||
The Android Firebase Firestore SDK is a large library, and in some scenarios it may bump you over the
|
||||
The Android Firebase Firestore SDK is a large library, and in some scenarios it may bump you over the
|
||||
65k method limit on the Android build system.
|
||||
|
||||
If you have added Cloud Firestore as a dependency and your application build is now failing with the following error,
|
||||
@@ -13,7 +13,7 @@ you'll need to [enable multidex](https://developer.android.com/studio/build/mult
|
||||
|
||||
## Enabling Multidex
|
||||
|
||||
Open the `/android/app/build.gradle` file. Under `dependencies` we need to add the module, and then enable it
|
||||
Open the `/android/app/build.gradle` file. Under `dependencies` we need to add the module, and then enable it
|
||||
within out `defaultConfig`:
|
||||
|
||||
```groovy
|
||||
|
||||
@@ -15,7 +15,7 @@ on our application.
|
||||
|
||||
# Setup state
|
||||
|
||||
First, setup a component which will display the list of data. The component will have 2 separate states; `loading` and
|
||||
First, setup a component which will display the list of data. The component will have 2 separate states; `loading` and
|
||||
`users`:
|
||||
|
||||
```jsx
|
||||
@@ -36,7 +36,7 @@ function Users() {
|
||||
|
||||
# useEffect hook
|
||||
|
||||
Next, we'll setup a hook with `useEffect`. This hook will trigger when our components mount, and we'll then subscribe to
|
||||
Next, we'll setup a hook with `useEffect`. This hook will trigger when our components mount, and we'll then subscribe to
|
||||
the "Users" collection documents:
|
||||
|
||||
```jsx
|
||||
@@ -49,9 +49,11 @@ function Users() {
|
||||
const [users, setUsers] = useState([]); // Initial empty array of users
|
||||
|
||||
useEffect(() => {
|
||||
const subscriber = firestore().collection('Users').onSnapshot(() => {
|
||||
// see next step
|
||||
});
|
||||
const subscriber = firestore()
|
||||
.collection('Users')
|
||||
.onSnapshot(() => {
|
||||
// see next step
|
||||
});
|
||||
|
||||
// Unsubscribe from events when no longer in use
|
||||
return () => subscriber();
|
||||
@@ -73,19 +75,21 @@ we can use the `id` of a document:
|
||||
|
||||
```js
|
||||
useEffect(() => {
|
||||
const subscriber = firestore().collection('Users').onSnapshot((querySnapshot) => {
|
||||
const users = [];
|
||||
|
||||
querySnapshot.forEach((documentSnapshot) => {
|
||||
users.push({
|
||||
...documentSnapshot.data(),
|
||||
key: documentSnapshot.id,
|
||||
});
|
||||
});
|
||||
const subscriber = firestore()
|
||||
.collection('Users')
|
||||
.onSnapshot(querySnapshot => {
|
||||
const users = [];
|
||||
|
||||
setUsers(users);
|
||||
setLoading(false);
|
||||
});
|
||||
querySnapshot.forEach(documentSnapshot => {
|
||||
users.push({
|
||||
...documentSnapshot.data(),
|
||||
key: documentSnapshot.id,
|
||||
});
|
||||
});
|
||||
|
||||
setUsers(users);
|
||||
setLoading(false);
|
||||
});
|
||||
|
||||
// Unsubscribe from events when no longer in use
|
||||
return () => subscriber();
|
||||
@@ -93,7 +97,7 @@ useEffect(() => {
|
||||
```
|
||||
|
||||
Once the initial set of documents is returned, we update the `users` state with our raw object data and set the `loading`
|
||||
state to `false`. We can now
|
||||
state to `false`. We can now
|
||||
|
||||
# Integration
|
||||
|
||||
@@ -126,4 +130,4 @@ function Users() {
|
||||
```
|
||||
|
||||
With little effort, our list will automatically update in realtime whenever a document is added/removed/modified!
|
||||
This functionality can be further manipulated to respond to user filters via [Querying](/firestore/usage#querying) if required.
|
||||
This functionality can be further manipulated to respond to user filters via [Querying](/firestore/usage#querying) if required.
|
||||
|
||||
@@ -30,19 +30,18 @@ for your application. To learn more, read the [Enabling Multidex](/firestore/ena
|
||||
|
||||
# What does it do
|
||||
|
||||
Firestore is a flexible, scalable NoSQL cloud database to store and sync data. It keeps your data in sync across client
|
||||
Firestore is a flexible, scalable NoSQL cloud database to store and sync data. It keeps your data in sync across client
|
||||
apps through realtime listeners and offers offline support so you can build responsive apps that work regardless of network
|
||||
latency or Internet connectivity.
|
||||
latency or Internet connectivity.
|
||||
|
||||
<Youtube id="QcsAb2RR52c" />
|
||||
|
||||
|
||||
|
||||
# Usage
|
||||
|
||||
## Collections & Documents
|
||||
|
||||
Cloud Firestore stores data within "documents", which are contained within "collections", and documents can also contain
|
||||
Cloud Firestore stores data within "documents", which are contained within "collections", and documents can also contain
|
||||
collections. For example, we could store a list of our users documents within a "Users" collection. The `collection` method
|
||||
allows us to reference a collection within our code:
|
||||
|
||||
@@ -60,7 +59,9 @@ on the collection by calling the `doc` method:
|
||||
import firestore from '@react-native-firebase/firestore';
|
||||
|
||||
// Get user document with an ID of ABC
|
||||
const userDocument = firestore().collection('Users').doc('ABC');
|
||||
const userDocument = firestore()
|
||||
.collection('Users')
|
||||
.doc('ABC');
|
||||
```
|
||||
|
||||
The `doc` method returns a [`DocumentReference`](/reference/firestore/documentreference).
|
||||
@@ -82,8 +83,13 @@ or [`DocumentReference`](/reference/firestore/documentreference):
|
||||
```js
|
||||
import firestore from '@react-native-firebase/firestore';
|
||||
|
||||
const users = await firestore().collection('Users').get();
|
||||
const user = await firestore().collection('Users').doc('ABC').get();
|
||||
const users = await firestore()
|
||||
.collection('Users')
|
||||
.get();
|
||||
const user = await firestore()
|
||||
.collection('Users')
|
||||
.doc('ABC')
|
||||
.get();
|
||||
```
|
||||
|
||||
### Realtime changes
|
||||
@@ -102,7 +108,9 @@ function onError(error) {
|
||||
console.error(error);
|
||||
}
|
||||
|
||||
firestore().collection('Users').onSnapshot(onResult, onError);
|
||||
firestore()
|
||||
.collection('Users')
|
||||
.onSnapshot(onResult, onError);
|
||||
```
|
||||
|
||||
The `onSnapshot` method also returns a function, allowing you to unsubscribe from events. This can be used within any
|
||||
@@ -117,9 +125,9 @@ function User({ userId }) {
|
||||
const subscriber = firestore()
|
||||
.collection('Users')
|
||||
.doc(userId)
|
||||
.onSnapshot((documentSnapshot) => {
|
||||
console.log('User data: ', documentSnapshot.data())
|
||||
});
|
||||
.onSnapshot(documentSnapshot => {
|
||||
console.log('User data: ', documentSnapshot.data());
|
||||
});
|
||||
|
||||
// Stop listening for updates when no longer required
|
||||
return () => subscriber();
|
||||
@@ -150,10 +158,10 @@ import firestore from '@react-native-firebase/firestore';
|
||||
firestore()
|
||||
.collection('Users')
|
||||
.get()
|
||||
.then((querySnapshot) => {
|
||||
.then(querySnapshot => {
|
||||
console.log('Total users: ', querySnapshot.size);
|
||||
|
||||
querySnapshot.forEach((documentSnapshot) => {
|
||||
|
||||
querySnapshot.forEach(documentSnapshot => {
|
||||
console.log('User ID: ', documentSnapshot.id, documentSnapshot.data());
|
||||
});
|
||||
});
|
||||
@@ -165,7 +173,7 @@ allows you to access specific information about a document (see below).
|
||||
#### DocumentSnapshot
|
||||
|
||||
A [`DocumentSnapshot`](/reference/firestore/documentsnapshot) is returned from a query to a specific document, or as part
|
||||
of the documents returned via a [`QuerySnapshot`](/reference/firestore/querysnapshot). The snapshot provides the ability
|
||||
of the documents returned via a [`QuerySnapshot`](/reference/firestore/querysnapshot). The snapshot provides the ability
|
||||
to view a documents data, metadata and whether a document actually exists.
|
||||
|
||||
To view a documents data, call the `data` method on the snapshot:
|
||||
@@ -177,12 +185,12 @@ firestore()
|
||||
.collection('Users')
|
||||
.doc('ABC')
|
||||
.get()
|
||||
.then((documentSnapshot) => {
|
||||
.then(documentSnapshot => {
|
||||
console.log('User exists: ', documentSnapshot.exists);
|
||||
|
||||
|
||||
if (documentSnapshot.exists) {
|
||||
console.log('User data: ', documentSnapshot.data());
|
||||
}
|
||||
}
|
||||
});
|
||||
```
|
||||
|
||||
@@ -198,15 +206,15 @@ firestore()
|
||||
.collection('Users')
|
||||
.doc('ABC')
|
||||
.get()
|
||||
.then((documentSnapshot) => getUserZipCode(documentSnapshot))
|
||||
.then((zipCode) => {
|
||||
.then(documentSnapshot => getUserZipCode(documentSnapshot))
|
||||
.then(zipCode => {
|
||||
console.log('Users zip code is: ', zipCode);
|
||||
});
|
||||
```
|
||||
|
||||
### Querying
|
||||
|
||||
Cloud Firestore offers advanced capabilities for querying collections.
|
||||
Cloud Firestore offers advanced capabilities for querying collections.
|
||||
|
||||
#### Filtering
|
||||
|
||||
@@ -216,10 +224,12 @@ equality checks and "in" queries. For example, to filter users where their age i
|
||||
```js
|
||||
firestore()
|
||||
.collection('Users')
|
||||
// Filter results
|
||||
// Filter results
|
||||
.where('age', '>=', 18)
|
||||
.get()
|
||||
.then((querySnapshot) => { /* ... */ })
|
||||
.then(querySnapshot => {
|
||||
/* ... */
|
||||
});
|
||||
```
|
||||
|
||||
Cloud Firestore also supports array membership queries. For example, to filter users who speak both English (en) or
|
||||
@@ -228,10 +238,12 @@ French (fr), use the `in` filter:
|
||||
```js
|
||||
firestore()
|
||||
.collection('Users')
|
||||
// Filter results
|
||||
// Filter results
|
||||
.where('languages', 'in', ['en', 'fr'])
|
||||
.get()
|
||||
.then((querySnapshot) => {/* ... */})
|
||||
.then(querySnapshot => {
|
||||
/* ... */
|
||||
});
|
||||
```
|
||||
|
||||
To learn more about all of the querying capabilities Cloud Firestore has to offer, view the
|
||||
@@ -249,7 +261,9 @@ firestore()
|
||||
// Limit results
|
||||
.limit(20)
|
||||
.get()
|
||||
.then((querySnapshot) => {/* ... */})
|
||||
.then(querySnapshot => {
|
||||
/* ... */
|
||||
});
|
||||
```
|
||||
|
||||
The above example both filters the users by age and limits the documents returned to 20.
|
||||
@@ -264,12 +278,14 @@ firestore()
|
||||
// Order results
|
||||
.orderBy('age', 'desc')
|
||||
.get()
|
||||
.then((querySnapshot) => {/* ... */})
|
||||
.then(querySnapshot => {
|
||||
/* ... */
|
||||
});
|
||||
```
|
||||
|
||||
The above example orders all user in the snapshot by age in descending order.
|
||||
|
||||
#### Start/End
|
||||
#### Start/End
|
||||
|
||||
To start and/or end the query at a specific point within the collection, you can pass either a value to the `startAt`,
|
||||
`endAt`, `startAfter` or `endBefore` methods. You must specify an order to use pointers, for example:
|
||||
@@ -281,7 +297,9 @@ firestore()
|
||||
.startAt(18)
|
||||
.endAt(30)
|
||||
.get()
|
||||
.then((querySnapshot) => {/* ... */})
|
||||
.then(querySnapshot => {
|
||||
/* ... */
|
||||
});
|
||||
```
|
||||
|
||||
The above query orders the users by age in descending order, but only returns users whose age is between 18 and 30.
|
||||
@@ -289,14 +307,19 @@ The above query orders the users by age in descending order, but only returns us
|
||||
You can further specify a [`DocumentSnapshot`](/reference/firestore/documentsnapshot) instead of a specific value. For example:
|
||||
|
||||
```js
|
||||
const userDocumentSnapshot = await firestore().collection('Users').doc('DEF').get();
|
||||
const userDocumentSnapshot = await firestore()
|
||||
.collection('Users')
|
||||
.doc('DEF')
|
||||
.get();
|
||||
|
||||
firestore()
|
||||
.collection('Users')
|
||||
.orderBy('age', 'desc')
|
||||
.startAt(userDocumentSnapshot)
|
||||
.get()
|
||||
.then((querySnapshot) => {/* ... */})
|
||||
.then(querySnapshot => {
|
||||
/* ... */
|
||||
});
|
||||
```
|
||||
|
||||
The above query orders the users by age in descending order, however only returns documents whose order starts at the user
|
||||
@@ -308,8 +331,8 @@ Cloud Firestore does not support the following types of queries:
|
||||
|
||||
- Queries with range filters on different fields, as described in the previous section.
|
||||
- Logical OR queries. In this case, you should create a separate query for each OR condition and merge the query results in your app.
|
||||
- Queries with a `!=` clause. In this case, you should split the query into a greater-than query and a less-than query.
|
||||
For example, although the query clause `where("age", "!=", "30")` is not supported, you can get the same result set by
|
||||
- Queries with a `!=` clause. In this case, you should split the query into a greater-than query and a less-than query.
|
||||
For example, although the query clause `where("age", "!=", "30")` is not supported, you can get the same result set by
|
||||
combining two queries, one with the clause `where("age", "<", "30")` and one with the clause `where("age", ">", 30)`.
|
||||
|
||||
## Writing Data
|
||||
@@ -337,7 +360,7 @@ firestore()
|
||||
});
|
||||
```
|
||||
|
||||
The `add` method adds the new document to your collection with a random unique ID. If you'd like to specify your own ID,
|
||||
The `add` method adds the new document to your collection with a random unique ID. If you'd like to specify your own ID,
|
||||
call the `set` method on a [`DocumentReference`](/reference/firestore/documentreference) instead:
|
||||
|
||||
```js
|
||||
@@ -362,15 +385,15 @@ if you'd like to update a document instead, use the `update` method:
|
||||
|
||||
```js
|
||||
import firestore from '@react-native-firebase/firestore';
|
||||
|
||||
|
||||
firestore()
|
||||
.collection('Users')
|
||||
.doc('ABC')
|
||||
.update({
|
||||
age: 31,
|
||||
age: 31,
|
||||
})
|
||||
.then(() => {
|
||||
console.log('User updated!');
|
||||
console.log('User updated!');
|
||||
});
|
||||
```
|
||||
|
||||
@@ -378,15 +401,15 @@ The method also provides support for updating deeply nested values via dot-notat
|
||||
|
||||
```js
|
||||
import firestore from '@react-native-firebase/firestore';
|
||||
|
||||
|
||||
firestore()
|
||||
.collection('Users')
|
||||
.doc('ABC')
|
||||
.update({
|
||||
'info.address.zipcode': 94040,
|
||||
'info.address.zipcode': 94040,
|
||||
})
|
||||
.then(() => {
|
||||
console.log('User updated!');
|
||||
console.log('User updated!');
|
||||
});
|
||||
```
|
||||
|
||||
@@ -402,8 +425,8 @@ class:
|
||||
firestore()
|
||||
.doc('users/ABC')
|
||||
.update({
|
||||
'info.address.location': new firestore.GeoPoint(53.483959, -2.244644),
|
||||
})
|
||||
'info.address.location': new firestore.GeoPoint(53.483959, -2.244644),
|
||||
});
|
||||
```
|
||||
|
||||
To store a [Blob](/reference/firestore/blob) (for example of a Base64 image string), provide the string to the static
|
||||
@@ -413,8 +436,8 @@ To store a [Blob](/reference/firestore/blob) (for example of a Base64 image stri
|
||||
firestore()
|
||||
.doc('users/ABC')
|
||||
.update({
|
||||
'info.avatar': firestore.Blob.fromBase64String('data:image/png;base64,iVBOR...'),
|
||||
})
|
||||
'info.avatar': firestore.Blob.fromBase64String('data:image/png;base64,iVBOR...'),
|
||||
});
|
||||
```
|
||||
|
||||
When storing timestamps, it is recommended you use the `serverTimestamp` static method on the [`FieldValue`](/reference/firestore/fieldvalue)
|
||||
@@ -426,11 +449,11 @@ firestore()
|
||||
.doc('users/ABC')
|
||||
.update({
|
||||
createdAt: firestore.FieldValue.serverTimestamp(),
|
||||
})
|
||||
});
|
||||
```
|
||||
|
||||
Cloud Firestore also allows for storing arrays. To help manage the values with an array (adding or removing) the API
|
||||
exposes an `arrayUnion` and `arrayRemove` methods on the [`FieldValue`](/reference/firestore/fieldvalue) class.
|
||||
exposes an `arrayUnion` and `arrayRemove` methods on the [`FieldValue`](/reference/firestore/fieldvalue) class.
|
||||
|
||||
To add a new value to an array (if it does not exist):
|
||||
|
||||
@@ -439,7 +462,7 @@ firestore()
|
||||
.doc('users/ABC')
|
||||
.update({
|
||||
fcmTokens: firestore.FieldValue.arrayUnion('ABCDE123456'),
|
||||
})
|
||||
});
|
||||
```
|
||||
|
||||
To remove a value from the array (if it exists):
|
||||
@@ -449,7 +472,7 @@ firestore()
|
||||
.doc('users/ABC')
|
||||
.update({
|
||||
fcmTokens: firestore.FieldValue.arrayRemove('ABCDE123456'),
|
||||
})
|
||||
});
|
||||
```
|
||||
|
||||
## Removing data
|
||||
@@ -458,20 +481,20 @@ You can delete documents within Cloud Firestore using the `delete` method on a [
|
||||
|
||||
```js
|
||||
import firestore from '@react-native-firebase/firestore';
|
||||
|
||||
|
||||
firestore()
|
||||
.collection('Users')
|
||||
.doc('ABC')
|
||||
.delete()
|
||||
.then(() => {
|
||||
console.log('User deleted!');
|
||||
console.log('User deleted!');
|
||||
});
|
||||
```
|
||||
|
||||
At this time, you cannot delete an entire collection without use of a Firebase Admin SDK.
|
||||
At this time, you cannot delete an entire collection without use of a Firebase Admin SDK.
|
||||
|
||||
> If a document contains any sub-collections, these will not be deleted from database. You must delete
|
||||
any sub-collections yourself.
|
||||
> any sub-collections yourself.
|
||||
|
||||
If you need to remove a specific property with a document, rather than the document itself, you can use the `delete`
|
||||
method on the [`FieldValue`](/reference/firestore/fieldvalue) class:
|
||||
@@ -482,13 +505,13 @@ firestore()
|
||||
.doc('ABC')
|
||||
.update({
|
||||
fcmTokens: firestore.FieldValue.delete(),
|
||||
})
|
||||
});
|
||||
```
|
||||
|
||||
## Transactions
|
||||
|
||||
Transactions are a away to always ensure a write occurs with the latest information available on the server. Transactions
|
||||
never partially apply writes & all writes execute at the end of a successful transaction.
|
||||
never partially apply writes & all writes execute at the end of a successful transaction.
|
||||
|
||||
Transactions are useful when you want to update a field's value based on its current value, or the value of some other field.
|
||||
If you simply want to write multiple documents without using the document's current state, a [batch write](#batch-write) would be more appropriate.
|
||||
@@ -501,7 +524,7 @@ When using transactions, note that:
|
||||
- Transactions will fail when the client is offline.
|
||||
|
||||
Imagine a scenario whereby an app has the ability to "Like" user posts. Whenever a user presses the "Like" button,
|
||||
a "likes" value (number of likes) on a "Posts" collection document increments. Without transactions, we'd first need to read
|
||||
a "likes" value (number of likes) on a "Posts" collection document increments. Without transactions, we'd first need to read
|
||||
the existing value and then increment that value in two separate operations.
|
||||
|
||||
On a high traffic application, the value on the server could already have changed by the time the operation sets a new value,
|
||||
@@ -517,26 +540,25 @@ import firestore from '@react-native-firebase/firestore';
|
||||
|
||||
function onPostLike(postId) {
|
||||
// Create a reference to the post
|
||||
const postReference = firestore().doc(`posts/${postId}`)
|
||||
const postReference = firestore().doc(`posts/${postId}`);
|
||||
|
||||
return firestore()
|
||||
.runTransaction(async (transaction) => {
|
||||
// Get post data first
|
||||
const postSnapshot = await transaction.get(postReference);
|
||||
return firestore().runTransaction(async transaction => {
|
||||
// Get post data first
|
||||
const postSnapshot = await transaction.get(postReference);
|
||||
|
||||
if (!postSnapshot.exists) {
|
||||
throw "Post does not exist!";
|
||||
}
|
||||
if (!postSnapshot.exists) {
|
||||
throw 'Post does not exist!';
|
||||
}
|
||||
|
||||
await transaction.update(postReference, {
|
||||
likes: postSnapshot.data().likes + 1,
|
||||
});
|
||||
await transaction.update(postReference, {
|
||||
likes: postSnapshot.data().likes + 1,
|
||||
});
|
||||
});
|
||||
}
|
||||
|
||||
onPostLike('ABC')
|
||||
.then(() => console.log('Post likes incremented via a transaction'))
|
||||
.catch((error) => console.error(error));
|
||||
.catch(error => console.error(error));
|
||||
```
|
||||
|
||||
## Batch write
|
||||
@@ -553,20 +575,21 @@ import firestore from '@react-native-firebase/firestore';
|
||||
|
||||
async function massDeleteUsers() {
|
||||
// Get all users
|
||||
const usersQuerySnapshot = await firestore().collection('Users').get();
|
||||
const usersQuerySnapshot = await firestore()
|
||||
.collection('Users')
|
||||
.get();
|
||||
|
||||
// Create a new batch instance
|
||||
const batch = firestore().batch();
|
||||
|
||||
usersQuerySnapshot.forEach((documentSnapshot) => {
|
||||
usersQuerySnapshot.forEach(documentSnapshot => {
|
||||
batch.delete(documentSnapshot.ref);
|
||||
});
|
||||
|
||||
return batch.commit();
|
||||
}
|
||||
|
||||
massDeleteUsers()
|
||||
.then(() => console.log('All users deleted in a single batch operation.'));
|
||||
massDeleteUsers().then(() => console.log('All users deleted in a single batch operation.'));
|
||||
```
|
||||
|
||||
## Secure your data
|
||||
@@ -577,7 +600,7 @@ follow the firebase Firestore documentation on [security](https://firebase.googl
|
||||
## Offline Capabilities
|
||||
|
||||
Firestore provides out of the box support for offline capabilities. When reading and writing data, Firestore uses a local
|
||||
database which synchronises automatically with the server. Firestore functionality continues when users are offline, and
|
||||
database which synchronises automatically with the server. Firestore functionality continues when users are offline, and
|
||||
automatically handles data migration to the server when they regain connectivity.
|
||||
|
||||
This functionality is enabled by default, however it can be disabled if you need it to be disabled (e.g. on apps containing
|
||||
@@ -592,4 +615,3 @@ function bootstrap() {
|
||||
});
|
||||
}
|
||||
```
|
||||
|
||||
|
||||
@@ -40,13 +40,13 @@ import io.invertase.firebase.firestore.ReactNativeFirebaseFirestorePackage;
|
||||
|
||||
Add the package to the registry:
|
||||
|
||||
```java
|
||||
````java
|
||||
protected List<ReactPackage> getPackages() {
|
||||
return Arrays.asList(
|
||||
new MainReactPackage(),
|
||||
new ReactNativeFirebaseFirestorePackage(),
|
||||
```// ..
|
||||
```
|
||||
````
|
||||
|
||||
In some scenarios, your Android build may fail with the `app:mergeDexDebug` error. This required that multidex is enabled
|
||||
for your application. To learn more, read the [Enabling Multidex](/firestore/enabling-multidex) documentation.
|
||||
|
||||
@@ -27,29 +27,29 @@ you can follow the manual installation steps for [iOS](/functions/usage/installa
|
||||
|
||||
# What does it do
|
||||
|
||||
Firebase Cloud Functions let you automatically run backend code in response to events triggered by Firebase features and
|
||||
HTTPS requests. Your code is stored in Google's cloud and runs in a managed environment. There's no need to manage and
|
||||
Firebase Cloud Functions let you automatically run backend code in response to events triggered by Firebase features and
|
||||
HTTPS requests. Your code is stored in Google's cloud and runs in a managed environment. There's no need to manage and
|
||||
scale your own servers.
|
||||
|
||||
<Youtube id="vr0Gfvp5v1A" />
|
||||
|
||||
After you write and deploy a function, Google's servers begin to manage the function immediately. You can fire the function
|
||||
directly with an HTTP request, via the Cloud Functions module, or in the case of background functions, Google's servers will listen for events and run
|
||||
directly with an HTTP request, via the Cloud Functions module, or in the case of background functions, Google's servers will listen for events and run
|
||||
the function when it is triggered.
|
||||
|
||||
For more information on use cases, view the [Firebase Cloud Functions](https://firebase.google.com/docs/functions/use-cases) documentation.
|
||||
|
||||
# Usage
|
||||
|
||||
The Cloud Functions module provides the functionality to directly trigger deployed HTTPs callable functions, without worrying
|
||||
about security or implementing a HTTP request library.
|
||||
|
||||
The Cloud Functions module provides the functionality to directly trigger deployed HTTPs callable functions, without worrying
|
||||
about security or implementing a HTTP request library.
|
||||
|
||||
Functions deployed to Firebase have unique names, allowing you to easily identify which endpoint you wish to send a request to.
|
||||
To learn more about deploying Functions to Firebase, view the [Writing & Deploying Functions](/functions/writing-deploying-functions) documentation.
|
||||
|
||||
## Calling an endpoint
|
||||
|
||||
Assuming we have a deployed a callable endpoint named `listProducts`, to call the endpoint the library exposes a
|
||||
Assuming we have a deployed a callable endpoint named `listProducts`, to call the endpoint the library exposes a
|
||||
`httpsCallable` method. For example:
|
||||
|
||||
```js
|
||||
|
||||
@@ -5,7 +5,7 @@ next: /messaging/usage
|
||||
previous: /functions/usage
|
||||
---
|
||||
|
||||
Cloud Functions are a powerful asset to a developers workflow, allowing you to build complex backend tasks with
|
||||
Cloud Functions are a powerful asset to a developers workflow, allowing you to build complex backend tasks with
|
||||
minimal maintenance overhead. The following page outlines the steps required for writing, testing & deploying Cloud Functions to your Firebase project.
|
||||
|
||||
# Environment Setup
|
||||
@@ -22,7 +22,7 @@ Once installed, login to Firebase with the CLI. This process will automatically
|
||||
firebase login
|
||||
```
|
||||
|
||||
Once logged in, create a new directory on your development environment. This will be used as our working directory
|
||||
Once logged in, create a new directory on your development environment. This will be used as our working directory
|
||||
where our Cloud Functions will be written and deployed from. Within this directory, run the following command from your
|
||||
terminal to initialize a new project structure:
|
||||
|
||||
@@ -30,7 +30,7 @@ terminal to initialize a new project structure:
|
||||
firebase init functions
|
||||
```
|
||||
|
||||
You will be offered two options for language support, for this tutorial select JavaScript. Allow the CLI to install
|
||||
You will be offered two options for language support, for this tutorial select JavaScript. Allow the CLI to install
|
||||
dependencies using npm. Once complete your project structure will look like this:
|
||||
|
||||
```
|
||||
@@ -66,7 +66,7 @@ npm install faker --save-dev
|
||||
|
||||
Now it's time to write your first Cloud Function! Open up the generated `functions/index.js` file in your chosen editor.
|
||||
The CLI has already imported the `firebase-functions` package required to build a Cloud Function. Firebase uses
|
||||
[named exports](https://developer.mozilla.org/en-US/docs/web/javascript/reference/statements/export) to help identify
|
||||
[named exports](https://developer.mozilla.org/en-US/docs/web/javascript/reference/statements/export) to help identify
|
||||
functions. These exports are used to build the API endpoint name which will be accessible from our React Native application.
|
||||
|
||||
For this tutorial, we are creating a product listing API. Go ahead and create a new HTTPS callable named function called products:
|
||||
@@ -112,7 +112,7 @@ exports.listProducts = functions.https.onCall((data, context) => {
|
||||
|
||||
## Testing functions
|
||||
|
||||
Before deploying our functions project, we can run the `serve` command which builds a locally accessible instance of our
|
||||
Before deploying our functions project, we can run the `serve` command which builds a locally accessible instance of our
|
||||
Cloud Functions. Run the following command from within the `functions/` directory:
|
||||
|
||||
```bash
|
||||
@@ -134,19 +134,16 @@ curl -i -H "Accept: application/json" -H "Content-Type: application/json" -X GET
|
||||
|
||||
## Security
|
||||
|
||||
By default the endpoint will be open to the public when deployed. Firebase offers an out-of-the-box solution for handling
|
||||
By default the endpoint will be open to the public when deployed. Firebase offers an out-of-the-box solution for handling
|
||||
authentication, which integrates with the [Authentication](/auth) module. To secure out endpoint, check whether the `auth`
|
||||
property exists on the endpoint:
|
||||
|
||||
```js
|
||||
exports.listProducts = functions.https.onCall((data, context) => {
|
||||
if (!context.auth) {
|
||||
throw new functions.https.HttpsError(
|
||||
'unauthenticated',
|
||||
'Endpoint requires authentication!',
|
||||
);
|
||||
throw new functions.https.HttpsError('unauthenticated', 'Endpoint requires authentication!');
|
||||
}
|
||||
|
||||
|
||||
return products;
|
||||
});
|
||||
```
|
||||
@@ -175,7 +172,7 @@ exports.listProducts = functions.https.onCall((data, context) => {
|
||||
const { page = 1, limit = 10 } = data;
|
||||
|
||||
const startAt = (page - 1) * limit;
|
||||
const endAt = startAt + limit;
|
||||
const endAt = startAt + limit;
|
||||
|
||||
return products.slice(startAt, endAt);
|
||||
});
|
||||
@@ -184,7 +181,7 @@ exports.listProducts = functions.https.onCall((data, context) => {
|
||||
# Deploying Functions
|
||||
|
||||
Once your functions are ready to be deployed, the project provides a `deploy` script which will upload all of your code
|
||||
onto the Firebase infrastructure and automatically provision production ready endpoints. Within the project, run the
|
||||
onto the Firebase infrastructure and automatically provision production ready endpoints. Within the project, run the
|
||||
`deploy` script from the `functions` directory:
|
||||
|
||||
```bash
|
||||
|
||||
@@ -27,8 +27,8 @@ you can follow the manual installation steps for [iOS](/iid/usage/installation/i
|
||||
|
||||
# What does it do
|
||||
|
||||
Instance ID provides a simple API to generate security tokens that authorize third parties to access your apps server side
|
||||
managed resources.
|
||||
Instance ID provides a simple API to generate security tokens that authorize third parties to access your apps server side
|
||||
managed resources.
|
||||
|
||||
An example of this is sending messages via Firebase Cloud Messaging.
|
||||
|
||||
@@ -47,7 +47,7 @@ async function getInstanceId() {
|
||||
}
|
||||
```
|
||||
|
||||
## Retrieving a token
|
||||
## Retrieving a token
|
||||
|
||||
Returns the token that authorizes performing actions on behalf of this application instance.
|
||||
|
||||
|
||||
@@ -27,9 +27,9 @@ you can follow the manual installation steps for [iOS](/in-app-messaging/usage/i
|
||||
|
||||
# What does it do
|
||||
|
||||
Firebase In-App Messaging helps you to engage your apps active users by sending them targeted, contextual messages that encourage
|
||||
them to use key app features. For example, you could send an in-app message to get users to subscribe, watch a video,
|
||||
complete a level, or buy an item. You can customize messages as cards, banners, modals, or images, and set up triggers
|
||||
Firebase In-App Messaging helps you to engage your apps active users by sending them targeted, contextual messages that encourage
|
||||
them to use key app features. For example, you could send an in-app message to get users to subscribe, watch a video,
|
||||
complete a level, or buy an item. You can customize messages as cards, banners, modals, or images, and set up triggers
|
||||
so that they appear exactly when they'd benefit your users most.
|
||||
|
||||
<Youtube id="5MRKpvKV2pg" />
|
||||
@@ -38,27 +38,27 @@ React Native Firebase provides support for both native Android & iOS integration
|
||||
|
||||
# Usage
|
||||
|
||||
Most of the set up occurs on [Firebase Console](https://console.firebase.google.com/u/0/project/_/inappmessaging) in the
|
||||
Most of the set up occurs on [Firebase Console](https://console.firebase.google.com/u/0/project/_/inappmessaging) in the
|
||||
`In-App Messaging` tab. You can create campaigns and customise elements such as Image, Banner, Modal & Cards to appear on
|
||||
pre-defined events (e.g. purchase). This involves no code for the developer to implement. Any published campaigns from the
|
||||
Firebase Console are automatically handled and displayed on your user's device.
|
||||
pre-defined events (e.g. purchase). This involves no code for the developer to implement. Any published campaigns from the
|
||||
Firebase Console are automatically handled and displayed on your user's device.
|
||||
|
||||
This module provides a JavaScript API to allow greater control of the displaying of these messages.
|
||||
This module provides a JavaScript API to allow greater control of the displaying of these messages.
|
||||
|
||||
## Displaying Messages
|
||||
|
||||
The `setMessagesDisplaySuppressed` method allows you to control when messages can/cannot be displayed. Below illustrates
|
||||
The `setMessagesDisplaySuppressed` method allows you to control when messages can/cannot be displayed. Below illustrates
|
||||
a use case for controlling the flow of messages:
|
||||
|
||||
>The suppressed state is not persisted between restarts, so ensure it is called as early as possible.
|
||||
> The suppressed state is not persisted between restarts, so ensure it is called as early as possible.
|
||||
|
||||
```jsx
|
||||
import inAppMessaging from '@react-native-firebase/in-app-messaging';
|
||||
|
||||
|
||||
async function bootstrap() {
|
||||
await inAppMessaging().setMessagesDisplaySuppressed(true);
|
||||
}
|
||||
|
||||
|
||||
async function onSetup(user) {
|
||||
await setupUser(user);
|
||||
// Allow user to receive messages now setup is complete
|
||||
@@ -73,7 +73,7 @@ async function onSetup(user) {
|
||||
In App Messaging can be further configured to enable or disable automatic data collection for Firebase In-App Messaging.
|
||||
|
||||
This is useful for opt-in-first data flows, for example when dealing with GDPR compliance. This can be overridden in JavaScript.
|
||||
This is possible by setting the below noted property on the `firebase.json` file at the root of your project directory.
|
||||
This is possible by setting the below noted property on the `firebase.json` file at the root of your project directory.
|
||||
|
||||
```json
|
||||
// <project-root>/firebase.json
|
||||
|
||||
@@ -94,7 +94,7 @@ to your project.
|
||||
On the Firebase console, add a new iOS application and enter your projects details. The "iOS bundle ID" must match your
|
||||
local project bundle ID. The bundle ID can be found within the "General" tab when opening the project with XCode.
|
||||
|
||||
Download the `GoogleService-Info.plist` file.
|
||||
Download the `GoogleService-Info.plist` file.
|
||||
|
||||
Using Xcode, open the projects `/ios/{projectName}.xcodeproj` file (or `/ios/{projectName}.xcworkspace` if using Pods).
|
||||
|
||||
@@ -156,7 +156,7 @@ you can follow the manual installation steps for [iOS](/install/ios) and [Androi
|
||||
|
||||
## Hermes Support
|
||||
|
||||
At this time, React Native Firebase does not support the [Hermes](https://hermesengine.dev/) JavaScript engine due to
|
||||
At this time, React Native Firebase does not support the [Hermes](https://hermesengine.dev/) JavaScript engine due to
|
||||
compatibility issues. We are actively tracking the changes to Hermes and will ensure support once both are compatible
|
||||
with each other.
|
||||
|
||||
@@ -186,15 +186,15 @@ project.ext {
|
||||
compileSdk: 28,
|
||||
buildTools: "28.0.3"
|
||||
],
|
||||
|
||||
|
||||
// Overriding Library SDK Versions
|
||||
firebase: [
|
||||
// Override Firebase SDK Version
|
||||
bom : "21.1.0",
|
||||
|
||||
|
||||
// Override Crashlytics SDK Version
|
||||
crashlytics : "2.10.0",
|
||||
|
||||
|
||||
// Override Crashlytics SDK Version
|
||||
crashlyticsNdk: "2.1.0"
|
||||
],
|
||||
@@ -212,10 +212,10 @@ Open your projects `/ios/Podfile` and add any of the globals shown below to the
|
||||
```ruby
|
||||
# Override Firebase SDK Version
|
||||
$FirebaseSDKVersion = '6.8.1'
|
||||
|
||||
|
||||
# Override Fabric SDK Version
|
||||
$FabricSDKVersion = '1.6.0'
|
||||
|
||||
|
||||
# Override Crashlytics SDK Version
|
||||
$CrashlyticsSDKVersion = '3.1.0'
|
||||
```
|
||||
@@ -242,4 +242,4 @@ support, add the following global to the top of your `/ios/Podfile` file:
|
||||
|
||||
```ruby
|
||||
$RNFirebaseAsStaticFramework = true
|
||||
```
|
||||
```
|
||||
|
||||
@@ -53,14 +53,14 @@ await messaging().requestPermission({
|
||||
|
||||
The full list of permission settings can be seen in the table below along with their default values:
|
||||
|
||||
| Permission | Default | Description |
|
||||
| --------------------------- | ------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
|
||||
| `alert` | `true` | Sets whether notifications can be displayed to the user on the device. |
|
||||
| `announcement` | `false` | If enabled, Siri will read the notification content out when devices are connected to AirPods. |
|
||||
| `badge` | `true` | Sets whether a notification dot will appear next to the app icon on the device when there are unread notifications. |
|
||||
| `carPlay` | `true` | Sets whether notifications will appear when the device is connected to [CarPlay](https://www.apple.com/ios/carplay/). |
|
||||
| `provisional` | `false` | Sets whether provisional permissions are granted. See [Provisional permission](#provisional-permission) for more information. |
|
||||
| `sound` | `true` | Sets whether a sound will be played when a notification is displayed on the device. |
|
||||
| Permission | Default | Description |
|
||||
| -------------- | ------- | ----------------------------------------------------------------------------------------------------------------------------- |
|
||||
| `alert` | `true` | Sets whether notifications can be displayed to the user on the device. |
|
||||
| `announcement` | `false` | If enabled, Siri will read the notification content out when devices are connected to AirPods. |
|
||||
| `badge` | `true` | Sets whether a notification dot will appear next to the app icon on the device when there are unread notifications. |
|
||||
| `carPlay` | `true` | Sets whether notifications will appear when the device is connected to [CarPlay](https://www.apple.com/ios/carplay/). |
|
||||
| `provisional` | `false` | Sets whether provisional permissions are granted. See [Provisional permission](#provisional-permission) for more information. |
|
||||
| `sound` | `true` | Sets whether a sound will be played when a notification is displayed on the device. |
|
||||
|
||||
The settings provided will be stored by the device and will be visible in the iOS Settings UI for your application.
|
||||
|
||||
@@ -115,11 +115,11 @@ async function getExistingSettings() {
|
||||
|
||||
Devices on iOS 12+ can take advantage of provisional permissions. This type of permission system allows for notification
|
||||
permission to be instantly granted without displaying a dialog. The permission allows notifications to be displayed quietly
|
||||
|
||||
- meaning they're only visible within the device notification center.
|
||||
|
||||
To enable provisional notifications, pass an object to the `requestPermission` method, with the `provisional` key set to `true`:
|
||||
|
||||
|
||||
```js
|
||||
await messaging().requestPermission({
|
||||
provisional: true,
|
||||
|
||||
@@ -49,7 +49,9 @@ to send [messages from a server](/messaging/server-integration), a `notification
|
||||
|
||||
```js
|
||||
await admin.messaging().sendMulticast({
|
||||
tokens: [/* ... */], // ['token_1', 'token_2', ...]
|
||||
tokens: [
|
||||
/* ... */
|
||||
], // ['token_1', 'token_2', ...]
|
||||
notification: {
|
||||
title: 'Basic Notification',
|
||||
body: 'This is a basic notification sent from the server!',
|
||||
@@ -124,17 +126,23 @@ function App() {
|
||||
useEffect(() => {
|
||||
// Assume a message-notification contains a "type" property in the data payload of the screen to open
|
||||
|
||||
messaging().onNotificationOpenedApp((remoteMessage) => {
|
||||
console.log('Notification caused app to open from background state:', remoteMessage.notification);
|
||||
messaging().onNotificationOpenedApp(remoteMessage => {
|
||||
console.log(
|
||||
'Notification caused app to open from background state:',
|
||||
remoteMessage.notification,
|
||||
);
|
||||
navigation.navigate(remoteMessage.data.type);
|
||||
});
|
||||
|
||||
// Check whether an initial notification is available
|
||||
messaging()
|
||||
.getInitialNotification()
|
||||
.then((remoteMessage) => {
|
||||
.then(remoteMessage => {
|
||||
if (remoteMessage) {
|
||||
console.log('Notification caused app to open from quit state:', remoteMessage.notification);
|
||||
console.log(
|
||||
'Notification caused app to open from quit state:',
|
||||
remoteMessage.notification,
|
||||
);
|
||||
setInitialRoute(remoteMessage.data.type); // e.g. "Settings"
|
||||
}
|
||||
setLoading(false);
|
||||
|
||||
@@ -57,15 +57,14 @@ function App() {
|
||||
// Get the device token
|
||||
messaging()
|
||||
.getToken()
|
||||
.then((token) => {
|
||||
.then(token => {
|
||||
return saveTokenToDatabase(token);
|
||||
});
|
||||
|
||||
// Listen to whether the token changes
|
||||
return messaging()
|
||||
.onTokenRefresh((token) => {
|
||||
saveTokenToDatabase(token);
|
||||
});
|
||||
return messaging().onTokenRefresh(token => {
|
||||
saveTokenToDatabase(token);
|
||||
});
|
||||
}, []);
|
||||
}
|
||||
```
|
||||
@@ -83,7 +82,7 @@ so it's important to ensure that we store all tokens in the database.
|
||||
With the tokens stored in a secure datastore, we now have the ability to send messages via FCM to those devices.
|
||||
|
||||
> The following example uses the Node.JS `firebase-admin` package to send messages to our devices, however any SDK (listed above)
|
||||
can be used.
|
||||
> can be used.
|
||||
|
||||
Go ahead and setup the [`firebase-tools`](https://www.npmjs.com/package/firebase-admin) library on your server environment.
|
||||
Once setup, our script needs to perform two actions:
|
||||
@@ -126,12 +125,14 @@ async function onUserPictureLiked(ownerId, userId, picture) {
|
||||
user: JSON.stringify(user),
|
||||
picture: JSON.stringify(picture),
|
||||
},
|
||||
}, {
|
||||
},
|
||||
{
|
||||
// Required for background/quit data-only messages on iOS
|
||||
contentAvailable: true,
|
||||
// Required for background/quit data-only messages on Android
|
||||
priority: 'high',
|
||||
});
|
||||
},
|
||||
);
|
||||
}
|
||||
```
|
||||
|
||||
@@ -168,7 +169,7 @@ or updating UI. The possibilities are endless!
|
||||
# Send messages to topics
|
||||
|
||||
When devices [subscribe to topics](/messaging/usage#topics), you can send messages without specifying/storing any device
|
||||
tokens.
|
||||
tokens.
|
||||
|
||||
Using the `firebase-admin` Admin SDK as an example, we can send a message to devices subscribed to a topic:
|
||||
|
||||
@@ -183,11 +184,13 @@ const message = {
|
||||
topic: 'weather',
|
||||
};
|
||||
|
||||
admin.messaging().send(message)
|
||||
.then((response) => {
|
||||
admin
|
||||
.messaging()
|
||||
.send(message)
|
||||
.then(response => {
|
||||
console.log('Successfully sent message:', response);
|
||||
})
|
||||
.catch((error) => {
|
||||
.catch(error => {
|
||||
console.log('Error sending message:', error);
|
||||
});
|
||||
```
|
||||
@@ -214,11 +217,13 @@ const message = {
|
||||
condition: "'weather' in topics && ('news' in topics || 'traffic' in topics)",
|
||||
};
|
||||
|
||||
admin.messaging().send(message)
|
||||
.then((response) => {
|
||||
admin
|
||||
.messaging()
|
||||
.send(message)
|
||||
.then(response => {
|
||||
console.log('Successfully sent message:', response);
|
||||
})
|
||||
.catch((error) => {
|
||||
.catch(error => {
|
||||
console.log('Error sending message:', error);
|
||||
});
|
||||
```
|
||||
|
||||
@@ -23,7 +23,7 @@ cd ios/ && pod install
|
||||
```
|
||||
|
||||
> iOS requires further configuration steps to be carried out before you can start receiving and sending
|
||||
messages through Firebase. Read the documentation on how to [setup iOS with Firebase Messagig](/messaging/usage/ios-setup).
|
||||
> messages through Firebase. Read the documentation on how to [setup iOS with Firebase Messagig](/messaging/usage/ios-setup).
|
||||
|
||||
If you're using an older version of React Native without auto-linking support, or wish to integrate into an existing project,
|
||||
you can follow the manual installation steps for [iOS](/messaging/usage/installation/ios) and [Android](/messaging/usage/installation/android).
|
||||
@@ -93,16 +93,16 @@ be used however you see fit within your application. Common use-cases for handli
|
||||
- Updating the application's UI.
|
||||
|
||||
> To learn about how to send messages to devices from your own server setup, view the
|
||||
[Server Integration](/messaging/server-integration) documentation.
|
||||
> [Server Integration](/messaging/server-integration) documentation.
|
||||
|
||||
Depending on the devices state, incoming messages are handled differently by the device and module. To understand these
|
||||
scenarios, it is first important to establish the various states a device can be in:
|
||||
|
||||
| State | Description |
|
||||
|----------------|--------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------|
|
||||
| **Foreground** | When the application is open and in view. |
|
||||
| State | Description |
|
||||
| -------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
|
||||
| **Foreground** | When the application is open and in view. |
|
||||
| **Background** | When the application is open, however in the background (minimised). This typically occurs when the user has pressed the "home" button on the device or has switched to another app via the app switcher. |
|
||||
| **Quit** | When the device is locked or application is not active or running. The user can quit an app by "swiping it away" via the app switcher UI on the device. |
|
||||
| **Quit** | When the device is locked or application is not active or running. The user can quit an app by "swiping it away" via the app switcher UI on the device. |
|
||||
|
||||
The user must have opened the app before messages can be received. If the user force quits the app from the device settings, it must be re-opened again before receiving messages.
|
||||
|
||||
@@ -113,14 +113,14 @@ Depending on the contents of the message, it's important to understand both how
|
||||
The device state and message contents determines which handler will be called:
|
||||
|
||||
| | Foreground | Background | Quit |
|
||||
|-------------------------|-------------|-------------------------------------------------|-------------------------------------------------|
|
||||
| ----------------------- | ----------- | ----------------------------------------------- | ----------------------------------------------- |
|
||||
| **Notification** | `onMessage` | `setBackgroundMessageHandler` | `setBackgroundMessageHandler` |
|
||||
| **Notification + Data** | `onMessage` | `setBackgroundMessageHandler` | `setBackgroundMessageHandler` |
|
||||
| **Data** | `onMessage` | `setBackgroundMessageHandler` (***see below***) | `setBackgroundMessageHandler` (***see below***) |
|
||||
| **Data** | `onMessage` | `setBackgroundMessageHandler` (**_see below_**) | `setBackgroundMessageHandler` (**_see below_**) |
|
||||
|
||||
* In cases where the message is data-only and the device is in the background or quit, both Android & iOS treat the message
|
||||
as low priority and will ignore it (i.e. no event will be sent). You can however increase the priority by setting the `priority` to `high` (Android) and
|
||||
`content-available` to `true` (iOS) properties on the payload.
|
||||
- In cases where the message is data-only and the device is in the background or quit, both Android & iOS treat the message
|
||||
as low priority and will ignore it (i.e. no event will be sent). You can however increase the priority by setting the `priority` to `high` (Android) and
|
||||
`content-available` to `true` (iOS) properties on the payload.
|
||||
|
||||
To learn more about how to send these options in your message payload, view the Firebase documentation for your [FCM API implementation](https://firebase.google.com/docs/cloud-messaging/concept-options).
|
||||
|
||||
@@ -128,11 +128,11 @@ To learn more about how to send these options in your message payload, view the
|
||||
|
||||
The device state and message contents can also determine whether a [Notification](/messaging/notifications) will be displayed:
|
||||
|
||||
| | Foreground | Background | Quit |
|
||||
|-------------------------|-----------------------------|------------------------|------------------------|
|
||||
| **Notification** | Notification: ❌ | Notification: ✅ | Notification: ✅ |
|
||||
| **Notification + Data** | Notification: ❌ | Notification: ✅ | Notification: ✅ |
|
||||
| **Data** | Notification: ❌ | Notification: ❌ | Notification: ❌ |
|
||||
| | Foreground | Background | Quit |
|
||||
| ----------------------- | ---------------------- | ---------------------- | ---------------------- |
|
||||
| **Notification** | Notification: ❌ | Notification: ✅ | Notification: ✅ |
|
||||
| **Notification + Data** | Notification: ❌ | Notification: ✅ | Notification: ✅ |
|
||||
| **Data** | Notification: ❌ | Notification: ❌ | Notification: ❌ |
|
||||
|
||||
### Foreground state messages
|
||||
|
||||
@@ -149,7 +149,7 @@ import messaging from '@react-native-firebase/messaging';
|
||||
|
||||
function App() {
|
||||
useEffect(() => {
|
||||
const unsubscribe = messaging().onMessage(async (remoteMessage) => {
|
||||
const unsubscribe = messaging().onMessage(async remoteMessage => {
|
||||
Alert.alert('A new FCM message arrived!', JSON.stringify(remoteMessage));
|
||||
});
|
||||
|
||||
@@ -213,12 +213,14 @@ admin.messaging().sendToDevice(
|
||||
user: JSON.stringify(user),
|
||||
picture: JSON.stringify(picture),
|
||||
},
|
||||
}, {
|
||||
// Required for background/quit data-only messages on iOS
|
||||
contentAvailable: true,
|
||||
// Required for background/quit data-only messages on Android
|
||||
priority: 'high',
|
||||
});
|
||||
},
|
||||
{
|
||||
// Required for background/quit data-only messages on iOS
|
||||
contentAvailable: true,
|
||||
// Required for background/quit data-only messages on Android
|
||||
priority: 'high',
|
||||
},
|
||||
);
|
||||
```
|
||||
|
||||
These options can be applied to all FCM messages. View the [Server Integration](/messaging/server-integration) documentation
|
||||
@@ -269,12 +271,12 @@ devices subscribed to that topic will receive the message.
|
||||
Topics allow you to simplify FCM [server integration](/messaging/server-integration) as you do not need to keep a store of
|
||||
device tokens. There are however some things to keep in mind about topics:
|
||||
|
||||
- Messages sent to topics should not contain sensitive or private information. Do not create a topic for a specific user
|
||||
to subscribe to.
|
||||
- Messages sent to topics should not contain sensitive or private information. Do not create a topic for a specific user
|
||||
to subscribe to.
|
||||
- Topic messaging supports unlimited subscriptions for each topic.
|
||||
- One app instance can be subscribed to no more than 2000 topics.
|
||||
- The frequency of new subscriptions is rate-limited per project. If you send too many subscription requests in a short
|
||||
period of time, FCM servers will respond with a 429 RESOURCE_EXHAUSTED ("quota exceeded") response. Retry with exponential backoff.
|
||||
- The frequency of new subscriptions is rate-limited per project. If you send too many subscription requests in a short
|
||||
period of time, FCM servers will respond with a 429 RESOURCE_EXHAUSTED ("quota exceeded") response. Retry with exponential backoff.
|
||||
- A server integration can send a single message to multiple topics at once. This however is limited to 5 topics.
|
||||
|
||||
To learn more about how to send messages to devices subscribed to topics, view the [Send messages to topics](/messaging/server-integration#send-messages-to-topics)
|
||||
|
||||
@@ -34,6 +34,7 @@ dependencies {
|
||||
Import and apply the React Native Firebase module package to your `/android/app/src/main/java/**/MainApplication.java` file:
|
||||
|
||||
### 3.1 Import the package
|
||||
|
||||
Add the following underneath
|
||||
`import com.facebook.react.ReactActivity;`:
|
||||
|
||||
@@ -42,6 +43,7 @@ import io.invertase.firebase.messaging.ReactNativeFirebaseMessagingPackage;
|
||||
```
|
||||
|
||||
### 3.2 Add the package to the registry
|
||||
|
||||
Add the following within the `MainActivity` class:
|
||||
|
||||
```java
|
||||
@@ -61,4 +63,3 @@ Once the above steps have been completed, rebuild your Android project:
|
||||
```bash
|
||||
npx react-native run-android
|
||||
```
|
||||
|
||||
|
||||
@@ -28,16 +28,15 @@ you can follow the manual installation steps for [iOS](/ml-natural-language/usag
|
||||
# What does it do
|
||||
|
||||
The React Native Firebase ML Natural Language module supports [Smart Replies](https://firebase.google.com/docs/ml-kit/generate-smart-replies)
|
||||
& [Language Identification](https://firebase.google.com/docs/ml-kit/identify-languages) provided by Firebase ML kit.
|
||||
& [Language Identification](https://firebase.google.com/docs/ml-kit/identify-languages) provided by Firebase ML kit.
|
||||
At this moment, the [Translation](https://firebase.google.com/docs/ml-kit/translation) module is not supported
|
||||
|
||||
<Youtube id="ejrn_JHksws" />
|
||||
|
||||
|
||||
Smart reply can automatically generate relevant replies to messages. It helps helps your users respond to messages quickly,
|
||||
and makes it easier to reply to messages on devices with limited input capabilities.
|
||||
|
||||
Language identification can be used to determine the language of a string of text. It can be useful when working with
|
||||
Language identification can be used to determine the language of a string of text. It can be useful when working with
|
||||
user-provided text, which often doesn't come with any language information.
|
||||
|
||||
# Usage
|
||||
@@ -47,7 +46,7 @@ for each service and usage examples of each.
|
||||
|
||||
## Smart Replies
|
||||
|
||||
The [Smart Replies](https://firebase.google.com/docs/ml-kit/generate-smart-replies) service from Firebase allows you to
|
||||
The [Smart Replies](https://firebase.google.com/docs/ml-kit/generate-smart-replies) service from Firebase allows you to
|
||||
generate suggested replies based on a list of on-going conversation data.
|
||||
|
||||
Before using the API, the Smart Reply model must be installed on your device. To enable installation of the model, set
|
||||
@@ -77,19 +76,21 @@ Once complete, the `suggestReplies` method allows you to generate potential repl
|
||||
which may generate three responses per input as example below:
|
||||
|
||||
```jsx
|
||||
const replies = await firebase.naturalLanguage().suggestReplies([
|
||||
{ text: 'Hey, long time no speak!', },
|
||||
{ text: 'I know right, it has been a while..', userId: '123', isLocalUser: false },
|
||||
{ text: 'We should catchup some time!', },
|
||||
{ text: 'Definitely, how about we go for lunch this week?', userId: '123', isLocalUser: false },
|
||||
]);
|
||||
const replies = await firebase
|
||||
.naturalLanguage()
|
||||
.suggestReplies([
|
||||
{ text: 'Hey, long time no speak!' },
|
||||
{ text: 'I know right, it has been a while..', userId: '123', isLocalUser: false },
|
||||
{ text: 'We should catchup some time!' },
|
||||
{ text: 'Definitely, how about we go for lunch this week?', userId: '123', isLocalUser: false },
|
||||
]);
|
||||
|
||||
replies.forEach(reply => {
|
||||
console.log(reply.text);
|
||||
});
|
||||
```
|
||||
|
||||
Each array item an is an instance of a [`TextMessage`](/reference/ml-natural-language/textmessage). At a minimum you
|
||||
Each array item an is an instance of a [`TextMessage`](/reference/ml-natural-language/textmessage). At a minimum you
|
||||
must provide the a `text` property. To help the Machine Learning service identify various users in the conversation, you
|
||||
can set the `isLocalUser` flag to `false` if the message is from an external user, along with a unique ID.
|
||||
|
||||
@@ -98,7 +99,7 @@ property from the returned [`SuggestedReply`](/reference/ml-natural-language/sug
|
||||
|
||||
## Identify language
|
||||
|
||||
The [Language Identification](https://firebase.google.com/docs/ml-kit/identify-languages) service from Firebase allows you to
|
||||
The [Language Identification](https://firebase.google.com/docs/ml-kit/identify-languages) service from Firebase allows you to
|
||||
identify a language from any given string of text.
|
||||
|
||||
Before using the API, the Language Identification model must be installed on your device. To enable installation of the model, set
|
||||
@@ -138,7 +139,7 @@ Add any of the keys indicated below to your `firebase.json` file at the root of
|
||||
true to enable them. All models and APIs are disabled (false) by default.
|
||||
|
||||
> If you are manually linking on iOS (e.g. not using CocoaPods) then it's up to you to manage these models and dependencies
|
||||
yourself - firebase.json support is only for Android and iOS (via Pods).
|
||||
> yourself - firebase.json support is only for Android and iOS (via Pods).
|
||||
|
||||
```json
|
||||
// <project-root>/firebase.json
|
||||
|
||||
@@ -5,12 +5,12 @@ next: /ml-vision/image-labelling
|
||||
previous: /ml-vision/landmark-recognition
|
||||
---
|
||||
|
||||
Barcode scanning can read data encoded using most standard barcode formats. Barcode scanning happens on the device,
|
||||
Barcode scanning can read data encoded using most standard barcode formats. Barcode scanning happens on the device,
|
||||
and doesn't require a network connection. It's a convenient way to pass information from the real world to your app.
|
||||
|
||||
The Machine Learning service is only offered on the device, and no cloud service exists.
|
||||
|
||||
Given an image file, the Barcode Scanning service will attempt to recognise one or more barcodes, offering information
|
||||
Given an image file, the Barcode Scanning service will attempt to recognise one or more barcodes, offering information
|
||||
such as:
|
||||
|
||||
- The 4-point coordinates of the barcodes on the image.
|
||||
@@ -54,8 +54,8 @@ import vision, { VisionBarcodeValueType } from '@react-native-firebase/ml-vision
|
||||
|
||||
async function processBarcodes(localPath) {
|
||||
const barcodes = await vision().barcodeDetectorProcessImage(localPath);
|
||||
|
||||
barcodes.forEach((barcode) => {
|
||||
|
||||
barcodes.forEach(barcode => {
|
||||
if (barcode.valueType === VisionBarcodeValueType.CALENDAR_EVENT) {
|
||||
console.log('Barcode is a calendar event: ', barcode.calendarEvent);
|
||||
}
|
||||
@@ -97,9 +97,8 @@ async function processBarcodes(localPath) {
|
||||
// Local path to file on the device
|
||||
const localFile = `${utils.FilePath.PICTURES_DIRECTORY}/barcode-document.jpg`;
|
||||
|
||||
processBarcodes(localFile)
|
||||
.then(() => console.log('Finished processing file.'));
|
||||
processBarcodes(localFile).then(() => console.log('Finished processing file.'));
|
||||
```
|
||||
|
||||
To learn about the types of information the barcode scanner can return, view the
|
||||
To learn about the types of information the barcode scanner can return, view the
|
||||
[`VisionBarcode`](/reference/ml-vision/visionbarcode) documentation.
|
||||
|
||||
@@ -5,13 +5,13 @@ next: /remote-config/usage
|
||||
previous: /ml-vision/face-detection
|
||||
---
|
||||
|
||||
Face detection can detect faces in an image, identify key facial features, and get the contours of detected faces.
|
||||
Face detection can detect faces in an image, identify key facial features, and get the contours of detected faces.
|
||||
This provides information needed to perform tasks like embellishing selfies and portraits, or generating avatars
|
||||
from a user's photo.
|
||||
|
||||
The Machine Learning service is only offered on the device, and no cloud service exists.
|
||||
|
||||
Given an image file, the Face Detection service will attempt to recognise one or faces, offering information
|
||||
Given an image file, the Face Detection service will attempt to recognise one or faces, offering information
|
||||
such as:
|
||||
|
||||
- Face contour coordinates.
|
||||
@@ -56,16 +56,16 @@ import vision, { VisionFaceContourType } from '@react-native-firebase/ml-vision'
|
||||
|
||||
async function processFaces(localPath) {
|
||||
const faces = await vision().faceDetectorProcessImage(localPath);
|
||||
|
||||
faces.forEach((face) => {
|
||||
|
||||
faces.forEach(face => {
|
||||
console.log('Head rotation on Y axis: ', face.headEulerAngleY);
|
||||
console.log('Head rotation on Z axis: ', face.headEulerAngleZ);
|
||||
|
||||
|
||||
console.log('Left eye open probability: ', face.leftEyeOpenProbability);
|
||||
console.log('Right eye open probability: ', face.rightEyeOpenProbability);
|
||||
console.log('Smiling probability: ', face.smilingProbability);
|
||||
|
||||
face.faceContours.forEach((contour) => {
|
||||
face.faceContours.forEach(contour => {
|
||||
if (contour.type === VisionFaceContourType.FACE) {
|
||||
console.log('Face outline points: ', contour.points);
|
||||
}
|
||||
@@ -76,9 +76,8 @@ async function processFaces(localPath) {
|
||||
// Local path to file on the device
|
||||
const localFile = `${utils.FilePath.PICTURES_DIRECTORY}/barcode-document.jpg`;
|
||||
|
||||
processBarcodes(localFile)
|
||||
.then(() => console.log('Finished processing file.'));
|
||||
processBarcodes(localFile).then(() => console.log('Finished processing file.'));
|
||||
```
|
||||
|
||||
To learn about the types of information the face detector can return, view the
|
||||
To learn about the types of information the face detector can return, view the
|
||||
[`VisionFace`](/reference/ml-vision/visionface) documentation.
|
||||
|
||||
@@ -5,10 +5,9 @@ next: /ml-vision/face-detection
|
||||
previous: /ml-vision/barcode-scanning
|
||||
---
|
||||
|
||||
Image labelling can recognize entities in an image without having to provide any additional contextual metadata, using
|
||||
Image labelling can recognize entities in an image without having to provide any additional contextual metadata, using
|
||||
either an on-device API or a cloud-based API. It gets a list of the entities that were recognized: people, things, places,
|
||||
activities, and so on.
|
||||
|
||||
activities, and so on.
|
||||
|
||||
# Cloud Image Labelling
|
||||
|
||||
@@ -22,7 +21,7 @@ import vision from '@react-native-firebase/ml-vision';
|
||||
async function processImage(localPath) {
|
||||
const labels = await vision().cloudImageLabelerProcessImage(localPath);
|
||||
|
||||
labels.forEach((label) => {
|
||||
labels.forEach(label => {
|
||||
console.log('Service labelled the image: ', label.text);
|
||||
console.log('Confidence in the label: ', label.confidence);
|
||||
});
|
||||
@@ -31,17 +30,16 @@ async function processImage(localPath) {
|
||||
// Local path to file on the device
|
||||
const localFile = `${utils.FilePath.PICTURES_DIRECTORY}/image-document.jpg`;
|
||||
|
||||
processImage(localFile)
|
||||
.then(() => console.log('Finished processing file.'));
|
||||
processImage(localFile).then(() => console.log('Finished processing file.'));
|
||||
```
|
||||
|
||||
To learn more about the available data on a processed document, view the [`VisionImageLabel`](/reference/ml-vision/visionimagelabel)
|
||||
documentation.
|
||||
|
||||
## Configuration
|
||||
|
||||
|
||||
By default, the service will return labels with any confidence level, which may include labels you do not care about or
|
||||
are too obvious. Set the `confidenceThreshold` key to a value between 0 & 1, where 1 represents 100% confidence. The
|
||||
are too obvious. Set the `confidenceThreshold` key to a value between 0 & 1, where 1 represents 100% confidence. The
|
||||
cloud service will only return labels with a confidence greater than what you specified:
|
||||
|
||||
```js
|
||||
@@ -56,7 +54,7 @@ View the [`VisionCloudImageLabelerOptions`](/reference/ml-vision/visioncloudimag
|
||||
# On-device Image Labelling
|
||||
|
||||
Running the ML Kit service on a device requires the `ml_vision_image_label_model` and `ml_vision_label_model` to be download to the device. Although the results
|
||||
of on-device processing will be faster and more accurate, including the model in your application will increase the size
|
||||
of on-device processing will be faster and more accurate, including the model in your application will increase the size
|
||||
of the application.
|
||||
|
||||
## Enable the model
|
||||
@@ -95,7 +93,7 @@ import vision from '@react-native-firebase/ml-vision';
|
||||
async function processImage(localPath) {
|
||||
const labels = await vision().imageLabelerProcessImage(localPath);
|
||||
|
||||
labels.forEach((label) => {
|
||||
labels.forEach(label => {
|
||||
console.log('Service labelled the image: ', label.text);
|
||||
console.log('Confidence in the label: ', label.confidence);
|
||||
});
|
||||
@@ -104,6 +102,5 @@ async function processImage(localPath) {
|
||||
// Local path to file on the device
|
||||
const localFile = `${utils.FilePath.PICTURES_DIRECTORY}/image-document.jpg`;
|
||||
|
||||
processImage(localFile)
|
||||
.then(() => console.log('Finished processing file.'));
|
||||
processImage(localFile).then(() => console.log('Finished processing file.'));
|
||||
```
|
||||
|
||||
@@ -10,7 +10,7 @@ with each landmark's geographic coordinates and the region of the image the land
|
||||
|
||||
The Machine Learning service is only offered as a cloud based one, and no on-device service exists.
|
||||
|
||||
Given an image file, the Landmark Recognition service will attempt to recognise one or more landmarks, offering information
|
||||
Given an image file, the Landmark Recognition service will attempt to recognise one or more landmarks, offering information
|
||||
such as:
|
||||
|
||||
- The 4-point coordinates of the landmarks on the image.
|
||||
@@ -30,7 +30,7 @@ import vision from '@react-native-firebase/ml-vision';
|
||||
async function processLandmarks(localPath) {
|
||||
const landmarks = await vision().cloudLandmarkRecognizerProcessImage(localPath);
|
||||
|
||||
landmarks.forEach((visionLandmark) => {
|
||||
landmarks.forEach(visionLandmark => {
|
||||
console.log('Landmark name: ', visionLandmark.landmark);
|
||||
console.log('Landmark locations: ', block.locations);
|
||||
console.log('Confidence score: ', block.confidence);
|
||||
@@ -40,14 +40,13 @@ async function processLandmarks(localPath) {
|
||||
// Local path to file on the device
|
||||
const localFile = `${utils.FilePath.PICTURES_DIRECTORY}/image-file.jpg`;
|
||||
|
||||
processLandmarks(localFile)
|
||||
.then(() => console.log('Finished processing file.'));
|
||||
processLandmarks(localFile).then(() => console.log('Finished processing file.'));
|
||||
```
|
||||
|
||||
## Configuration
|
||||
|
||||
To help speed up requests and improve results, the `cloudLandmarkRecognizerProcessImage` method accepts an optional
|
||||
configuration object.
|
||||
configuration object.
|
||||
|
||||
```js
|
||||
import vision, { VisionCloudLandmarkRecognizerModelType } from '@react-native-firebase/ml-vision';
|
||||
|
||||
@@ -30,8 +30,8 @@ async function processDocument(localPath) {
|
||||
const processed = await vision().cloudDocumentTextRecognizerProcessImage(localPath);
|
||||
|
||||
console.log('Found text in document: ', processed.text);
|
||||
|
||||
processed.blocks.forEach((block) => {
|
||||
|
||||
processed.blocks.forEach(block => {
|
||||
console.log('Found block with text: ', block.text);
|
||||
console.log('Confidence in block: ', block.confidence);
|
||||
console.log('Languages found in block: ', block.recognizedLanguages);
|
||||
@@ -41,8 +41,7 @@ async function processDocument(localPath) {
|
||||
// Local path to file on the device
|
||||
const localFile = `${utils.FilePath.PICTURES_DIRECTORY}/text-document.jpg`;
|
||||
|
||||
processDocument(localFile)
|
||||
.then(() => console.log('Finished processing file.'));
|
||||
processDocument(localFile).then(() => console.log('Finished processing file.'));
|
||||
```
|
||||
|
||||
To learn more about the available data on a processed document, view the [`VisionDocumentText`](/reference/ml-vision/visiondocumenttext)
|
||||
@@ -68,7 +67,7 @@ View the [`VisionCloudDocumentTextRecognizerOptions`](/reference/ml-vision/visio
|
||||
# On-device Text Recognition
|
||||
|
||||
Running the ML Kit service on a device requires the `ml_vision_ocr_model` to be download to the device. Although the results
|
||||
of on-device processing will be faster and more accurate, including the model in your application will increase the size
|
||||
of on-device processing will be faster and more accurate, including the model in your application will increase the size
|
||||
of the application.
|
||||
|
||||
## Enable the model
|
||||
@@ -107,8 +106,8 @@ async function processDocument(localPath) {
|
||||
const processed = await vision().textRecognizerProcessImage(localPath);
|
||||
|
||||
console.log('Found text in document: ', processed.text);
|
||||
|
||||
processed.blocks.forEach((block) => {
|
||||
|
||||
processed.blocks.forEach(block => {
|
||||
console.log('Found block with text: ', block.text);
|
||||
console.log('Confidence in block: ', block.confidence);
|
||||
console.log('Languages found in block: ', block.recognizedLanguages);
|
||||
@@ -118,6 +117,5 @@ async function processDocument(localPath) {
|
||||
// Local path to file on the device
|
||||
const localFile = `${utils.FilePath.PICTURES_DIRECTORY}/text-document.jpg`;
|
||||
|
||||
processDocument(localFile)
|
||||
.then(() => console.log('Finished processing file.'));
|
||||
processDocument(localFile).then(() => console.log('Finished processing file.'));
|
||||
```
|
||||
|
||||
@@ -40,16 +40,16 @@ Depending on the service, it is possible to perform Machine Learning on both the
|
||||
The table below outlines the current module support for each available service, and whether they are available on local device,
|
||||
cloud or both.
|
||||
|
||||
| API | Cloud Model | On Device |
|
||||
|-----------------------------------------------------------------------------------------------|-------------|------------|
|
||||
| [Text Recognition](https://firebase.google.com/docs/ml-kit/recognize-text) | ✅ | ✅ |
|
||||
| [Document Text Recognition](https://firebase.google.com/docs/ml-kit/recognize-text)) | ✅ | |
|
||||
| [Face Detection](https://firebase.google.com/docs/ml-kit/detect-faces) | | ✅ |
|
||||
| [Barcode Scanning](https://firebase.google.com/docs/ml-kit/read-barcodes) | | ✅ |
|
||||
| [Image Labelling](https://firebase.google.com/docs/ml-kit/label-images) | ✅ | ✅ |
|
||||
| [Landmark Recognition](https://firebase.google.com/docs/ml-kit/recognize-landmarks) | | ✅ |
|
||||
| [AutoML Vision Edge](https://firebase.google.com/docs/ml-kit/automl-image-labeling) | ❌ | ❌ |
|
||||
| [Object Detection/Tracking](https://firebase.google.com/docs/ml-kit/object-detection) | ❌ | ❌ |
|
||||
| API | Cloud Model | On Device |
|
||||
| ------------------------------------------------------------------------------------- | ----------- | --------- |
|
||||
| [Text Recognition](https://firebase.google.com/docs/ml-kit/recognize-text) | ✅ | ✅ |
|
||||
| [Document Text Recognition](https://firebase.google.com/docs/ml-kit/recognize-text)) | ✅ | |
|
||||
| [Face Detection](https://firebase.google.com/docs/ml-kit/detect-faces) | | ✅ |
|
||||
| [Barcode Scanning](https://firebase.google.com/docs/ml-kit/read-barcodes) | | ✅ |
|
||||
| [Image Labelling](https://firebase.google.com/docs/ml-kit/label-images) | ✅ | ✅ |
|
||||
| [Landmark Recognition](https://firebase.google.com/docs/ml-kit/recognize-landmarks) | | ✅ |
|
||||
| [AutoML Vision Edge](https://firebase.google.com/docs/ml-kit/automl-image-labeling) | ❌ | ❌ |
|
||||
| [Object Detection/Tracking](https://firebase.google.com/docs/ml-kit/object-detection) | ❌ | ❌ |
|
||||
|
||||
# Usage
|
||||
|
||||
|
||||
@@ -71,7 +71,7 @@ axios.interceptors.response.use(
|
||||
|
||||
// Ensure failed requests throw after interception
|
||||
return Promise.reject(error);
|
||||
}
|
||||
},
|
||||
);
|
||||
```
|
||||
|
||||
|
||||
@@ -27,7 +27,7 @@ you can follow the manual installation steps for [iOS](/perf/usage/installation/
|
||||
|
||||
## Add the Performance Monitoring Plugin
|
||||
|
||||
On Android, you need to install the Google Performance Monitoring Plugin which enables automatic
|
||||
On Android, you need to install the Google Performance Monitoring Plugin which enables automatic
|
||||
HTTPs network request monitoring.
|
||||
|
||||
Add the plugin to your `/android/build.gradle` file as a dependency:
|
||||
@@ -54,13 +54,13 @@ It provides a simple API to track custom trace and HTTP request metrics.
|
||||
|
||||
<Youtube id="0EHSPFvH7vk" />
|
||||
|
||||
Review and analyze that data in the Firebase console. Performance Monitoring helps you to understand where and when the
|
||||
Review and analyze that data in the Firebase console. Performance Monitoring helps you to understand where and when the
|
||||
performance of your app can be improved so that you can use that information to fix performance issues.
|
||||
|
||||
Performance Monitoring package automatically traces events and metrics which are sent to Firebase. For more information
|
||||
on the automatic traces, please see the Firebase Performance Monitoring [documentation](https://firebase.google.com/docs/perf-mon/auto_duration-traces-metrics_ios-android).
|
||||
Performance Monitoring package automatically traces events and metrics which are sent to Firebase. For more information
|
||||
on the automatic traces, please see the Firebase Performance Monitoring [documentation](https://firebase.google.com/docs/perf-mon/auto_duration-traces-metrics_ios-android).
|
||||
The package also allows you to performance monitor custom aspects to your application like network requests & task specific
|
||||
app code. All performance metrics are available on your Firebase [console](https://console.firebase.google.com/u/0/) performance tab.
|
||||
app code. All performance metrics are available on your Firebase [console](https://console.firebase.google.com/u/0/) performance tab.
|
||||
|
||||
# Usage
|
||||
|
||||
@@ -70,15 +70,15 @@ Below is how you would measure the amount of time it would take to complete a sp
|
||||
|
||||
```jsx
|
||||
import perf from '@react-native-firebase/perf';
|
||||
|
||||
|
||||
async function customTrace() {
|
||||
// Define & start a trace
|
||||
const trace = await perf().startTrace('custom_trace');
|
||||
|
||||
|
||||
// Define trace meta details
|
||||
trace.putAttribute('user', 'abcd');
|
||||
trace.putMetric('credits', 30);
|
||||
|
||||
|
||||
// Stop the trace
|
||||
await trace.stop();
|
||||
}
|
||||
@@ -90,29 +90,29 @@ Below illustrates you would measure the latency of a HTTP request.
|
||||
|
||||
```jsx
|
||||
import perf from '@react-native-firebase/perf';
|
||||
|
||||
|
||||
async function getRequest(url) {
|
||||
// Define the network metric
|
||||
const metric = await perf().newHttpMetric(url, 'GET');
|
||||
|
||||
|
||||
// Define meta details
|
||||
metric.putAttribute('user', 'abcd');
|
||||
|
||||
|
||||
// Start the metric
|
||||
await metric.start();
|
||||
|
||||
|
||||
// Perform a HTTP request and provide response information
|
||||
const response = await fetch(url);
|
||||
metric.setHttpResponseCode(response.status);
|
||||
metric.setResponseContentType(response.headers.get('Content-Type'));
|
||||
metric.setResponsePayloadSize(response.headers.get('Content-Length'));
|
||||
|
||||
|
||||
// Stop the metric
|
||||
await metric.stop();
|
||||
|
||||
|
||||
return response.json();
|
||||
}
|
||||
|
||||
|
||||
// Call API
|
||||
getRequest('https://api.com').then(json => {
|
||||
console.log(json);
|
||||
|
||||
@@ -56,4 +56,3 @@ Once the above steps have been completed, rebuild your Android project:
|
||||
```bash
|
||||
npx react-native run-android
|
||||
```
|
||||
|
||||
|
||||
@@ -7,8 +7,8 @@ previous: /releases
|
||||
|
||||
Using the table below, you can find the release notes for the latest library releases.
|
||||
|
||||
| Version | |
|
||||
|---------|:--------------------------------------:|
|
||||
| Version | |
|
||||
| ------- | :--------------------------------------------: |
|
||||
| v6.4.0 | [View Release Notes »](/releases/v6.4.0) |
|
||||
| v6.3.0 | [View Release Notes »](/releases/v6.3.0) |
|
||||
| v6.2.0 | [View Release Notes »](/releases/v6.2.0) |
|
||||
|
||||
@@ -14,8 +14,8 @@ with most modules now just 'install and go'.
|
||||
|
||||
The new modules:
|
||||
|
||||
| Name | Downloads | Coverage |
|
||||
| -------------------------------------------------- | :---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------: | :-------------------------------------------------------------------------------------------------------------------------------------: |
|
||||
| Name | Downloads | Coverage |
|
||||
| ----------------------------------------------- | :---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------: | :-------------------------------------------------------------------------------------------------------------------------------------: |
|
||||
| [Analytics](/analytics) | [](https://www.npmjs.com/package/@react-native-firebase/analytics) | [](https://api.rnfirebase.io/coverage/analytics/detail) |
|
||||
| [App](/app) | [](https://www.npmjs.com/package/@react-native-firebase/app) | [](https://api.rnfirebase.io/coverage/app/detail) |
|
||||
| [Cloud Functions](/functions) | [](https://www.npmjs.com/package/@react-native-firebase/functions) | [](https://api.rnfirebase.io/coverage/functions/detail) |
|
||||
|
||||
@@ -2,4 +2,3 @@
|
||||
title: v6.4.0 Release
|
||||
description: Upgrade to Messaging & bug fixes
|
||||
---
|
||||
|
||||
|
||||
@@ -1,4 +1,3 @@
|
||||
---
|
||||
redirect: /remote-config/usage
|
||||
---
|
||||
|
||||
|
||||
@@ -39,7 +39,7 @@ To get started, you need to define some parameters over on the [Firebase Console
|
||||
|
||||

|
||||
|
||||
Each parameter is assigned a unique "key" and values. The values can be broken down to target specific conditions (such as Android or iOS). In the above example,
|
||||
Each parameter is assigned a unique "key" and values. The values can be broken down to target specific conditions (such as Android or iOS). In the above example,
|
||||
only Android devices would receive `enabled` for the `awesome_new_feature` parameter.
|
||||
|
||||
## Default values
|
||||
@@ -47,10 +47,9 @@ only Android devices would receive `enabled` for the `awesome_new_feature` param
|
||||
Before fetching the parameters from Firebase, it is first important to set some default values. Default values
|
||||
help ensure that your application code runs as expected in scenarios where the device has not yet retrieved the values.
|
||||
|
||||
|
||||
An example of this is having no network or you have not yet fetched them within your own code.
|
||||
|
||||
Setting default values helps to ensure that both the local device & Firebase servers are both in sync. Call the
|
||||
Setting default values helps to ensure that both the local device & Firebase servers are both in sync. Call the
|
||||
`setDefaults` method early on in your application:
|
||||
|
||||
```js
|
||||
@@ -83,18 +82,18 @@ remoteConfig()
|
||||
awesome_new_feature: 'disabled',
|
||||
})
|
||||
.then(() => remoteConfig().fetchAndActivate())
|
||||
.then((activated) => {
|
||||
.then(activated => {
|
||||
if (activated) {
|
||||
console.log('Defaults set, fetched & activated!');
|
||||
console.log('Defaults set, fetched & activated!');
|
||||
} else {
|
||||
console.log('Defaults set, however activation failed.');
|
||||
console.log('Defaults set, however activation failed.');
|
||||
}
|
||||
});
|
||||
```
|
||||
|
||||
## Reading values
|
||||
|
||||
With the defaults set and the remote values fetched from Firebase, we can now use the `getValue` method to get the
|
||||
With the defaults set and the remote values fetched from Firebase, we can now use the `getValue` method to get the
|
||||
value by it's key. For example...
|
||||
|
||||
```js
|
||||
@@ -140,7 +139,7 @@ Although Remote Config is a data-store, it is not designed for frequent reads -
|
||||
(default is 12 hours). By design, this prevents the values being able to change frequently and potentially cause users
|
||||
confusion.
|
||||
|
||||
You can however specify your own cache length by specifically calling the `fetch` method with the number of seconds to
|
||||
You can however specify your own cache length by specifically calling the `fetch` method with the number of seconds to
|
||||
cache the values for:
|
||||
|
||||
```js
|
||||
|
||||
@@ -37,8 +37,8 @@ global redundancy. Storage lets you securely upload these files directly from mo
|
||||
# Usage
|
||||
|
||||
Your files are stored in a Google Cloud Storage bucket. The files in this bucket are presented in a hierarchical structure,
|
||||
just like a file system. By creating a reference to a file, your app gains access to it. These references can then be
|
||||
used to upload or download data, get or update metadata or delete the file. A reference can either point to a specific
|
||||
just like a file system. By creating a reference to a file, your app gains access to it. These references can then be
|
||||
used to upload or download data, get or update metadata or delete the file. A reference can either point to a specific
|
||||
file or to a higher level node in the hierarchy.
|
||||
|
||||
The Storage module also provides support for multiple buckets.
|
||||
@@ -102,7 +102,7 @@ such as the current upload progress:
|
||||
```js
|
||||
const task = reference.putFile(pathToFile);
|
||||
|
||||
task.on('state_changed', (taskSnapshot) => {
|
||||
task.on('state_changed', taskSnapshot => {
|
||||
console.log(`${taskSnapshot.bytesTransferred} transferred out of ${task.totalBytes}`);
|
||||
});
|
||||
|
||||
@@ -124,7 +124,7 @@ task.resume();
|
||||
|
||||
## Download URLs
|
||||
|
||||
A common use-case for Cloud Storage is to use it as a global Content Delivery Network (CDN) for your images. When uploading
|
||||
A common use-case for Cloud Storage is to use it as a global Content Delivery Network (CDN) for your images. When uploading
|
||||
files to a bucket, they are not automatically available for consumption via a HTTP URL. To generate a new Download URL, you
|
||||
need to call the `getDownloadURL` method on a reference:
|
||||
|
||||
@@ -145,32 +145,30 @@ the `list` method. The results are however paginated, and if more results are av
|
||||
import storage from '@react-native-firebase/storage';
|
||||
|
||||
function listFilesAndDirectories(reference, pageToken) {
|
||||
return reference.list({ pageToken })
|
||||
.then((result) => {
|
||||
// Loop over each item
|
||||
result.items.forEach((ref) => {
|
||||
console.log(ref.fullPath);
|
||||
});
|
||||
|
||||
if (result.nextPageToken) {
|
||||
return listFilesAndDirectories(reference, result.nextPageToken);
|
||||
}
|
||||
|
||||
return Promise.resolve();
|
||||
return reference.list({ pageToken }).then(result => {
|
||||
// Loop over each item
|
||||
result.items.forEach(ref => {
|
||||
console.log(ref.fullPath);
|
||||
});
|
||||
|
||||
if (result.nextPageToken) {
|
||||
return listFilesAndDirectories(reference, result.nextPageToken);
|
||||
}
|
||||
|
||||
return Promise.resolve();
|
||||
});
|
||||
}
|
||||
|
||||
const reference = storage().ref('images');
|
||||
|
||||
listFilesAndDirectories(reference)
|
||||
.then(() => {
|
||||
console.log('Finished listing');
|
||||
});
|
||||
```
|
||||
listFilesAndDirectories(reference).then(() => {
|
||||
console.log('Finished listing');
|
||||
});
|
||||
```
|
||||
|
||||
## Security
|
||||
|
||||
By default your bucket will come with rules which allows only authenticated users on your project to access it. You can
|
||||
By default your bucket will come with rules which allows only authenticated users on your project to access it. You can
|
||||
however fully customise the security rules to your own applications requirements.
|
||||
|
||||
To learn more, view the [Storage Security](https://firebase.google.com/docs/storage/security/start) documentation
|
||||
@@ -179,8 +177,8 @@ on the Firebase website.
|
||||
## Multiple Buckets
|
||||
|
||||
A single Firebase project can have multiple storage buckets. The module will use the default bucket if no bucket argument
|
||||
is passed to the `storage` instance. To switch buckets, provide the module with the `gs://` bucket URL found on the
|
||||
Firebase Console, under Storage > Files.
|
||||
is passed to the `storage` instance. To switch buckets, provide the module with the `gs://` bucket URL found on the
|
||||
Firebase Console, under Storage > Files.
|
||||
|
||||
```js
|
||||
import storage from '@react-native-firebase/storage';
|
||||
|
||||
8
docs/typedoc.json
vendored
8
docs/typedoc.json
vendored
@@ -42351,10 +42351,6 @@
|
||||
}
|
||||
]
|
||||
},
|
||||
"overwrites": {
|
||||
"type": "reference",
|
||||
"name": "Error.stack"
|
||||
},
|
||||
"inheritedFrom": {
|
||||
"type": "reference",
|
||||
"name": "Error.stack"
|
||||
@@ -66541,10 +66537,6 @@
|
||||
}
|
||||
]
|
||||
},
|
||||
"overwrites": {
|
||||
"type": "reference",
|
||||
"name": "Error.stack"
|
||||
},
|
||||
"inheritedFrom": {
|
||||
"type": "reference",
|
||||
"name": "Error.stack"
|
||||
|
||||
2
docs/typedoc.min.json
vendored
2
docs/typedoc.min.json
vendored
File diff suppressed because one or more lines are too long
@@ -2,7 +2,7 @@
|
||||
title: TypeScript
|
||||
description: Using TypeScript with React Native Firebase
|
||||
next: /migrating-to-v6
|
||||
previous:
|
||||
previous:
|
||||
---
|
||||
|
||||
The React Native Firebase project comes with support for TypeScript. The project provides
|
||||
@@ -53,7 +53,7 @@ TypeScript will no longer show any errors, allowing us to safely continue develo
|
||||
|
||||
It is also possible to access the module types directly, if you need to locally reference variables within your own codebase.
|
||||
|
||||
For example, we may need to store the `User` in local state. Manually defining a type for local state TypeScript loses the ability to type check the code.
|
||||
For example, we may need to store the `User` in local state. Manually defining a type for local state TypeScript loses the ability to type check the code.
|
||||
|
||||
We can easily access the types manually through the module though, for example:
|
||||
|
||||
@@ -63,8 +63,8 @@ import { useEffect, useState } from 'react';
|
||||
import auth, { FirebaseAuthTypes } from '@react-native-firebase/auth';
|
||||
|
||||
function App() {
|
||||
const [loading, setLoading] = useState<boolean>(true);
|
||||
const [user, setUser] = useState<FirebaseAuthTypes.User | null>(null);
|
||||
const [loading, setLoading] = useState < boolean > true;
|
||||
const [user, setUser] = (useState < FirebaseAuthTypes.User) | (null > null);
|
||||
|
||||
useEffect(() => {
|
||||
auth().onAuthStateChanged(userState => {
|
||||
|
||||
Reference in New Issue
Block a user