firebase upload multiple files differance transaction android
Edit Page
Cloud Firestore
Installation and getting started with Firestore.
Installation
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.
# Install & setup the app module yarn add together @react-native-firebase/app # Install the firestore module yarn add @react-native-firebase/firestore # If you're developing your app using iOS, run this command cd ios/ && pod install
If you're using an older version of React Native without autolinking support, or wish to integrate into an existing project, y'all can follow the manual installation steps for iOS and Android.
If you have started to receive a app:mergeDexDebug
fault after adding Deject Firestore, delight read the Enabling Multidex documentation for more information on how to resolve this fault.
What does it practise
Firestore is a flexible, scalable NoSQL cloud database to store and sync data. It keeps your information in sync across customer apps through realtime listeners and offers offline support so you tin build responsive apps that work regardless of network latency or Internet connectivity.
Usage
Collections & Documents
Deject 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" drove. The collection
method allows u.s. to reference a drove within our code:
import firestore from '@react-native-firebase/firestore' ; const usersCollection = firestore ( ) . drove ( 'Users' ) ;
The collection
method returns a CollectionReference
class, which provides properties and methods to query and fetch the data from Cloud Firestore. We can too directly reference a single document on the drove by calling the doc
method:
import firestore from '@react-native-firebase/firestore' ; // Get user certificate with an ID of ABC const userDocument = firestore ( ) . drove ( 'Users' ) . doctor ( 'ABC' ) ;
The doc
method returns a DocumentReference
.
A document can comprise different types of data, including scalar values (strings, booleans, numbers), arrays (lists) and objects (maps) forth with specific Cloud Firestore information such as Timestamps, GeoPoints, Blobs and more.
Read Data
Cloud Firestore provides the power to read the value of a collection or certificate. This can be read erstwhile, or provide realtime updates when the information inside a query changes.
1-time read
To read a collection or document once, call the get
method on a CollectionReference
or DocumentReference
:
import firestore from '@react-native-firebase/firestore' ; const users = await firestore ( ) . collection ( 'Users' ) . go ( ) ; const user = await firestore ( ) . drove ( 'Users' ) . doc ( 'ABC' ) . get ( ) ;
Realtime changes
To setup an agile listener to react to whatever changes to the query, call the onSnapshot
method with an event handler callback. For example, to watch the entire "Users" collection for when any documents are changed (removed, added, modified):
import firestore from '@react-native-firebase/firestore' ; function onResult ( QuerySnapshot ) { console . log ( 'Got Users collection event.' ) ; } part onError ( fault ) { console . error (error) ; } firestore ( ) . collection ( 'Users' ) . onSnapshot (onResult, onError) ;
The onSnapshot
method also returns a role, allowing y'all to unsubscribe from events. This tin can be used inside any useEffect
hooks to automatically unsubscribe when the hook needs to unsubscribe itself:
import React , { useEffect } from 'react' ; import firestore from '@react-native-firebase/firestore' ; function User ( { userId } ) { useEffect ( ( ) => { const subscriber = firestore ( ) . drove ( 'Users' ) . medico (userId) . onSnapshot ( documentSnapshot => { console . log ( 'User data: ' , documentSnapshot. information ( ) ) ; } ) ; // Stop listening for updates when no longer required return ( ) => subscriber ( ) ; } , [userId] ) ; }
Realtime changes via the onSnapshot
method can be applied to both collections and documents.
Snapshots
Once a query has returned a result, Firestore returns either a QuerySnapshot
(for collection queries) or a DocumentSnapshot
(for document queries). These snapshots provide the ability to view the information, view query metadata (such as whether the data was from local enshroud), whether the certificate exists or non and more.
QuerySnapshot
A QuerySnapshot
returned from a collection query allows you to inspect the collection, such equally how many documents be within it, access to the documents inside the collection, whatsoever changes since the last query and more.
To access the documents within a QuerySnapshot
, call the forEach
method:
import firestore from '@react-native-firebase/firestore' ; firestore ( ) . collection ( 'Users' ) . get ( ) . then ( querySnapshot => { console . log ( 'Total users: ' , querySnapshot. size ) ; querySnapshot. forEach ( documentSnapshot => { console . log ( 'User ID: ' , documentSnapshot. id , documentSnapshot. data ( ) ) ; } ) ; } ) ;
Each child certificate of a QuerySnapshot
is a QueryDocumentSnapshot
, which allows you to access specific information most a document (run across below).
DocumentSnapshot
A DocumentSnapshot
is returned from a query to a specific certificate, or equally part of the documents returned via a QuerySnapshot
. The snapshot provides the ability to view a documents data, metadata and whether a certificate actually exists.
To view a documents data, telephone call the data
method on the snapshot:
import firestore from '@react-native-firebase/firestore' ; firestore ( ) . collection ( 'Users' ) . doc ( 'ABC' ) . become ( ) . and so ( documentSnapshot => { panel . log ( 'User exists: ' , documentSnapshot. exists ) ; if (documentSnapshot. exists ) { console . log ( 'User information: ' , documentSnapshot. data ( ) ) ; } } ) ;
A snapshot also provides a helper function to easily access deeply nested data within a certificate. Call the get
method with a dot-notated path:
role getUserZipCode ( documentSnapshot ) { return documentSnapshot. get ( 'info.address.zipcode' ) ; } firestore ( ) . collection ( 'Users' ) . medico ( 'ABC' ) . become ( ) . and then ( documentSnapshot => getUserZipCode (documentSnapshot) ) . and so ( zipCode => { console . log ( 'Users zip code is: ' , zipCode) ; } ) ;
Querying
Cloud Firestore offers advanced capabilities for querying collections.
Filtering
To filter documents within a collection, the where
method can exist chained onto a collection reference. Filtering supports equality checks and "in" queries. For example, to filter users where their age is greater or equal than 18 years old:
firestore ( ) . collection ( 'Users' ) // Filter results . where ( 'historic period' , '>=' , eighteen ) . become ( ) . and so ( querySnapshot => { /* ... */ } ) ;
Deject Firestore also supports assortment membership queries. For example, to filter users who speak both English language (en) or French (fr), use the in
filter:
firestore ( ) . collection ( 'Users' ) // Filter results . where ( 'languages' , 'in' , [ 'en' , 'fr' ] ) . get ( ) . then ( querySnapshot => { /* ... */ } ) ;
To larn more about all of the querying capabilities Cloud Firestore has to offering, view the Firebase documentation.
Limiting
To limit the number of documents returned from a query, use the limit
method on a drove reference:
firestore ( ) . collection ( 'Users' ) // Filter results . where ( 'age' , '>=' , eighteen ) // Limit results . limit ( 20 ) . get ( ) . then ( querySnapshot => { /* ... */ } ) ;
The to a higher place example both filters the users by age and limits the documents returned to xx.
Ordering
To order the documents by a specific value, use the orderBy
method:
firestore ( ) . collection ( 'Users' ) // Order results . orderBy ( 'age' , 'desc' ) . get ( ) . and then ( querySnapshot => { /* ... */ } ) ;
The higher up example orders all user in the snapshot by age in descending order.
Start/End
To get-go and/or stop the query at a specific point within the collection, yous can pass either a value to the startAt
, endAt
, startAfter
or endBefore
methods. You must specify an order to apply pointers, for case:
firestore ( ) . collection ( 'Users' ) . orderBy ( 'age' , 'desc' ) . startAt ( 18 ) . endAt ( xxx ) . go ( ) . then ( querySnapshot => { /* ... */ } ) ;
The above query orders the users by historic period in descending society, but only returns users whose age is betwixt 18 and xxx.
You lot can further specify a DocumentSnapshot
instead of a specific value. For instance:
const userDocumentSnapshot = await firestore ( ) . collection ( 'Users' ) . doc ( 'DEF' ) . get ( ) ; firestore ( ) . collection ( 'Users' ) . orderBy ( 'age' , 'desc' ) . startAt (userDocumentSnapshot) . get ( ) . then ( querySnapshot => { /* ... */ } ) ;
The above query orders the users by age in descending order, however only returns documents whose order starts at the user with an ID of DEF
.
Query Limitations
Cloud Firestore does non support the following types of queries:
- Queries with range filters on unlike fields, every bit described in the previous department.
- Logical OR queries. In this case, you should create a carve up query for each OR status and merge the query results in your app.
Writing Data
The Firebase documentation provides great examples on best practices on how to construction your data. Nosotros highly recommend reading the guide before edifice out your database.
For a more in-depth look at what is possible when writing data to Firestore please refer to this documentation
Adding documents
To add together a new certificate to a drove, use the add
method on a CollectionReference
:
import firestore from '@react-native-firebase/firestore' ; firestore ( ) . drove ( 'Users' ) . add ( { proper noun: 'Ada Lovelace' , historic period: 30 , } ) . and so ( ( ) => { console . log ( 'User added!' ) ; } ) ;
The add
method adds the new document to your drove with a random unique ID. If y'all'd like to specify your own ID, telephone call the fix
method on a DocumentReference
instead:
import firestore from '@react-native-firebase/firestore' ; firestore ( ) . collection ( 'Users' ) . md ( 'ABC' ) . set ( { name: 'Ada Lovelace' , age: xxx , } ) . then ( ( ) => { console . log ( 'User added!' ) ; } ) ;
Updating documents
The ready
method exampled in a higher place replaces whatever existing information on a given DocumentReference
. if you'd like to update a document instead, use the update
method:
import firestore from '@react-native-firebase/firestore' ; firestore ( ) . collection ( 'Users' ) . medico ( 'ABC' ) . update ( { age: 31 , } ) . so ( ( ) => { console . log ( 'User updated!' ) ; } ) ;
The method besides provides support for updating deeply nested values via dot-notation:
import firestore from '@react-native-firebase/firestore' ; firestore ( ) . collection ( 'Users' ) . doc ( 'ABC' ) . update ( { 'info.address.zipcode' : 94040 , } ) . so ( ( ) => { panel . log ( 'User updated!' ) ; } ) ;
Field values
Cloud Firestore supports storing and manipulating values on your database, such every bit Timestamps, GeoPoints, Blobs and assortment management.
To store GeoPoint
values, provide the breadth and longitude to a new instance of the course:
firestore ( ) . physician ( 'users/ABC' ) . update ( { 'info.address.location' : new firestore.GeoPoint ( 53.483959 , - 2.244644 ) , } ) ;
To store a Blob (for case of a Base64
paradigm string), provide the string to the static fromBase64String
method on the class:
firestore ( ) . doc ( 'users/ABC' ) . update ( { 'info.avatar' : firestore. Blob . fromBase64String ( 'data:paradigm/png;base64,iVBOR...' ) , } ) ;
When storing timestamps, it is recommended y'all use the serverTimestamp
static method on the FieldValue
grade. When written to the database, the Firebase servers will write a new timestamp based on their time, rather than the clients. This helps resolve whatsoever data consistency issues with different client timezones:
firestore ( ) . doc ( 'users/ABC' ) . update ( { createdAt: firestore. FieldValue . serverTimestamp ( ) , } ) ;
Cloud Firestore also allows for storing arrays. To assist manage the values with an array (adding or removing) the API exposes an arrayUnion
and arrayRemove
methods on the FieldValue
class.
To add together a new value to an array (if value does not exist, will not add indistinguishable values):
firestore ( ) . doc ( 'users/ABC' ) . update ( { fcmTokens: firestore. FieldValue . arrayUnion ( 'ABCDE123456' ) , } ) ;
To remove a value from the array (if the value exists):
firestore ( ) . doc ( 'users/ABC' ) . update ( { fcmTokens: firestore. FieldValue . arrayRemove ( 'ABCDE123456' ) , } ) ;
Removing data
Yous tin can delete documents inside Cloud Firestore using the delete
method on a DocumentReference
:
import firestore from '@react-native-firebase/firestore' ; firestore ( ) . collection ( 'Users' ) . doc ( 'ABC' ) . delete ( ) . then ( ( ) => { console . log ( 'User deleted!' ) ; } ) ;
At this time, you cannot delete an entire drove without apply of a Firebase Admin SDK.
If a document contains any sub-collections, these will not be deleted from database. You must delete whatever sub-collections yourself.
If you demand to remove a specific property with a document, rather than the certificate itself, you can utilise the delete
method on the FieldValue
form:
firestore ( ) . collection ( 'Users' ) . physician ( 'ABC' ) . update ( { fcmTokens: firestore. FieldValue . delete ( ) , } ) ;
Transactions
Transactions are a fashion to always ensure a write occurs with the latest data available on the server. Transactions never partially apply writes & all writes execute at the finish of a successful transaction.
Transactions are useful when y'all want to update a field'south value based on its current value, or the value of another field. If you simply want to write multiple documents without using the document's current state, a batch write would be more than appropriate.
When using transactions, note that:
- Read operations must come before write operations.
- A part calling a transaction (transaction part) might run more than one time if a concurrent edit affects a document that the transaction reads.
- Transaction functions should not directly alter application land (return a value from the
updateFunction
). - Transactions will fail when the client is offline.
Imagine a scenario whereby an app has the ability to "Similar" user posts. Whenever a user presses the "Like" button, a "likes" value (number of likes) on a "Posts" drove document increments. Without transactions, we'd first demand to read the existing value and then increase that value in two separate operations.
On a high traffic application, the value on the server could already accept changed by the time the operation sets a new value, causing the bodily number to not exist consistent.
Transactions remove this outcome by atomically updating the value on the server. If the value changes whilst the transaction is executing, information technology will retry. This ever ensures the value on the server is used rather than the client value.
To execute a new transaction, phone call the runTransaction
method:
import firestore from '@react-native-firebase/firestore' ; function onPostLike ( postId ) { // Create a reference to the post const postReference = firestore ( ) . medico ( ` posts/ ${postId} ` ) ; render firestore ( ) . runTransaction ( async transaction => { // Get post data start const postSnapshot = await transaction. get (postReference) ; if ( !postSnapshot. exists ) { throw 'Mail service does non exist!' ; } transaction. update (postReference, { likes: postSnapshot. information ( ) . likes + i , } ) ; } ) ; } onPostLike ( 'ABC' ) . then ( ( ) => panel . log ( 'Post likes incremented via a transaction' ) ) . grab ( error => console . error (mistake) ) ;
Batch write
If yous practice non need to read any documents in your performance gear up, you tin execute multiple write operations equally a single batch that contains any combination of set
, update
, or delete
operations. A batch of writes completes atomically and tin can write to multiple documents.
Starting time, create a new batch example via the batch
method, perform operations on the batch and finally commit information technology once set up. The example beneath shows how to delete all documents in a collection in a single performance:
import firestore from '@react-native-firebase/firestore' ; async function massDeleteUsers ( ) { // Get all users const usersQuerySnapshot = expect firestore ( ) . collection ( 'Users' ) . get ( ) ; // Create a new batch instance const batch = firestore ( ) . batch ( ) ; usersQuerySnapshot. forEach ( documentSnapshot => { batch. delete (documentSnapshot. ref ) ; } ) ; render batch. commit ( ) ; } massDeleteUsers ( ) . and then ( ( ) => console . log ( 'All users deleted in a single batch operation.' ) ) ;
Secure your data
It is important that you sympathize how to write rules in your Firebase console to ensure that your information is secure. Delight follow the Firebase Firestore documentation on security.
Offline Capabilities
Firestore provides out of the box support for offline capabilities. When reading and writing information, Firestore uses a local database which synchronizes 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 (eastward.g. on apps containing sensitive data). The settings()
method must be called before any Firestore interaction is performed, otherwise it volition only accept effect on the next app launch:
import firestore from '@react-native-firebase/firestore' ; async role bootstrap ( ) { await firestore ( ) . settings ( { persistence: fake , // disable offline persistence } ) ; }
Source: https://rnfirebase.io/firestore/usage
0 Response to "firebase upload multiple files differance transaction android"
Post a Comment