Kuidas luua React Native App ja integreerida see Firebase'iga

Selles õpetuses ehitame välja rakenduse React Native, mis on integreeritud Firebase'i taustaprogrammiga. Rakendus toetab nii React Native CLI kui ka Expo CLI-d.

See React Native Firebase'i õpetus hõlmab selliseid põhifunktsioone nagu autentimine, registreerimine ja andmebaasi (Firestore) CRUD-toimingud.

Võite ka kogu lähtekoodi Githubist alla laadida, kui soovite otse koodi sisse hüpata.

Selles õpetuses tutvustatakse järgmiste jaotiste üksikasju:

  1. Firebase'i projekti loomine
  2. Uue rakenduse React Native loomine ja konfigureerimine
  3. Kausta struktuuri, marsruutide ja navigeerimise seadistamine
  4. Kasutajaliidese juurutamine sisselogimise, registreerimise ja avakuvade jaoks
  5. Registreerumine Firebase Auth'is
  6. Logige sisse Firebase Authiga
  7. Püsivad sisselogimisandmed
  8. Firebase Firestore'i andmete kirjutamine ja lugemine

Alustame pikemalt mõtlemata projekti React Native Firebase väljaehitamist. Lõplik mobiilirakendus näeb välja selline:

reageerida kohalikule tuletõrjebaasile

1. Looge Firebase'i projekt

Avage Firebase.com ja looge uus konto. Kui olete sisse loginud, saate Firebase'i konsoolis luua uue projekti.

  • Looge Firebase.com-is uus konto
  • Looge Firebase'i konsoolis uus projekt
  • Luba Firebase Console'is e-posti ja parooli autentimise meetod -> Autentimine -> Sisselogimismeetod
  • Looge uus iOS-i rakendus rakenduse ID com.reactnativefirebase abil
  • (Valikuline) Looge uus Androidi rakendus paketi nimega com.reactnativefirebase
  • Laadige arvutisse alla järgmise sammuna loodud konfiguratsioonifail ( GoogleService-Info.plist iOS - i jaoks ja google-services.json Android -i jaoks)

Firebase võimaldab teil luua taustata rakendusi. See on toode, mis töötab Google Cloudi peal ja võimaldab arendajatel ehitada veebi- ja mobiilirakendusi ilma oma servereid vajamata.

See säästab palju aega, kuna teil pole vaja taustaprogrammi kirjutada. See on ka väga skaleeritav, seda toetab Google'i infrastruktuur.

Firebase'is saate salvestada kõik, mis on teie rakenduse jaoks vajalik - kasutajad, andmed, failid, tõukemärguannete märgid jne. Kogu see teave tehakse mobiiliklientidele kättesaadavaks Firebase SDK-de kaudu, mis ühilduvad React Native'iga . See tähendab, et kõik interaktsioonid taustaprogrammiga on abstraktsed ja kapseldatud SDK-sse, seega ei pea mobiiliarendajad muretsema API-kõnede, andmete parsimise, pistikupesade haldamise jne pärast.

2. Looge ja seadistage uus React Native App

Muudame oma rakenduse React Native Firebase ühilduvaks nii Expo CLI kui ka React Native CLI-ga.

Hakkame praegu kasutama Expo programmi, kuna see muudab uustulnukate jaoks oma rakenduste eelvaate hõlpsaks. Kuid me ei kasuta ühtegi Expo-spetsiifilist teeki, nii et src- koodi saab lihtsalt kasutada mis tahes rakenduses React Native, olenemata selle tellingutest.

Kasutame Firebase Web SDK-d, mis ühildub nii Expo kui ka React Native CLI-ga ja mida Google toetab otse.

Kui soovite selle asemel kasutada reaktiiv-native-firebase'i, installige see julgelt ja konfigureerige (kood on endiselt sama). Kuid pidage meeles, et me ei soovita seda mõnel põhjusel.

  • Google ei toeta seda otseselt, seega on selle hooldamine palju raskem, kuna see on lisakiht, mis võib põhjustada vigu, ja
  • see ei tööta ka Expo-ga, mis võib olla paljude arendajate jaoks tehingumurdja.

Allpool olevaid samme käsitletakse ka ametlikus React Native'i dokumentatsioonis, kuidas oma dev-keskkonda seadistada.

  • Installige Expo CLI

Juhtige oma terminalis lihtsalt

npm install -g expo-cli
  • Looge uus React Native rakendus, käivitades
expo init react-native-firebase 

Malli jaoks valige hallatud töövoog  -  tühi

  • Käivitage rakendus käivitades
yarn ios // or yarn android 

See annab teile ka QR-koodi, mille saate skannida iOS-i kaamera rakenduse või Androidi Expo rakenduse abil.

See on hea. Nüüd on meil uus rakendus React Native, mis töötab nii iOS-is kui ka Androidis. Alustame selle ühendamist teie Firebase'i taustaprogrammiga.

  • Lisage Firebase SDK React Native projekti
yarn add firebase 
  • Lisage React Native Navigation kogu käivitades
yarn add @react-navigation/native && yarn add @react-navigation/stack && expo install react-native-gesture-handler react-native-reanimated react-native-screens react-native-safe-area-context @react-native-community/masked-view
  • Lisage mitmesuguseid projektis kasutatavaid kasutajaliidese komponente ja pakette
yarn add react-native-keyboard-aware-scroll-view base-64 

Looge Firebase'i konfiguratsioonifail

mkdir src src/firebase && touch src/firebase/config.js

Lisage oma firebase'i konfiguratsioon kausta src / firebase / config.js:

You can get all this information from Firebase Console -> Project Settings

3. Create the Folder Structure and Set Up Routes and Navigation

  • Create the folder structure by running
mkdir src/screens src/screens/LoginScreen src/screens/RegistrationScreen src/screens/HomeScreen
  • Create the files structure by running
touch src/screens/index.js src/screens/LoginScreen/LoginScreen.js src/screens/LoginScreen/styles.js src/screens/RegistrationScreen/RegistrationScreen.js src/screens/styles.js src/screens/HomeScreen/HomeScreen.js src/screens/HomeScreen/styles.js
  • Add this code to src/screens/index.js
export { default as LoginScreen } from './LoginScreen/LoginScreen' export { default as HomeScreen } from './HomeScreen/HomeScreen' export { default as RegistrationScreen } from './RegistrationScreen/RegistrationScreen' 

Don’t worry if the project is broken! Everything will make sense in a little while.

  • Set up the routes & navigators

Override App.js file with the following code snippet:

4. Implement the UI

Now that we have the scaffold of the app, let’s go ahead and implement the UI components of all screens. We’re not going into the details of flex layout and React Native styling, since that is outside the scope for this tutorial. We’re going to focus mostly on React Native Firebase integration.

Simply override the files as follows:

  • src/LoginScreen/LoginScreen.js
  • src/LoginScreen/styles.js
  • src/RegistrationScreen/RegistrationScreen.js
  • src/RegistrationScreen/styles.js
  • src/HomeScreen/HomeScreen.js
  • src/HomeScreen/styles.js

At this point, your app should run properly and display the following screens (UI only):

reageeri natiivse tuletõrjebaasi autentimisele

You can switch between the two screens by tapping the links buttons in the footer.

Now that we have a beautiful UI for login and sign up, let’s see how we can integrate our React Native (and Expo) app with Firebase.

5. React Native Firebase — Registration

Let’s start with creating a new account with Firebase Auth, since naturally login comes after. For this, we are going to add the Firebase logic for creating a new account with email & password in RegistrationScreen.js, by implementing the onRegisterPress method as follows:

In the account creation flow above, we do a few important things:

  • We call Firebase Auth’s createUserWithEmailAndPassword API (line 13), which creates a new account that will show up in Firebase Console -> Authentication table.
  • If the account registration was successful, we also store the user data in Firebase Firestore (line 24). This is necessary for storing extra user information, such as full name, profile photo URL, and so on, which cannot be stored in the Authentication table.
  • If registration was successful, we navigate to the Home Screen, by passing in the user object data as well.
  • If any error occurs, we simply show an alert with it. Errors can be things such as no network connection, password too short, email invalid, and so on.

Reload your app and test the registration. If you successfully created one account, check that it shows up in Firebase Console ->Authentication:

6. React Native Firebase — Login

Now that we are able to create new accounts, let’s implement the login functionality. Firebase SDK takes care of all the authorization and authentication steps needed for a secure login.

Open LoginScreen.js, import firebase and complete the onLoginPress method:

Reload your app and go ahead and login with an existing account. The app should take you to the home screen if the credentials were correct, or it will alert you with an error if anything went wrong.

7. Persist Login Credentials

You’ll notice that if you quit the app and open it again, it will show the login screen again. For a good user experience, we’d want to land all logged in users on the Home screen. No one wants to type in their login credentials every time they want to use an app.

This is also known as persistent login. Fortunately, Firebase SDK takes care of this for us, dealing with all the security concerns. Persistent login is enabled by default in Firebase, so all we need to do is fetch the currently logged in user.

Open App.js and let’s implement the persistent login feature:

onAuthStateChanged returns the currently logged in user. We then fetch all the extra user data that we stored in Firestore, and set it on the current component’s state. This will re-render the app component, which will display the Home screen.

Notice how we call this the first time the app loads by leveraging the useEffect hook.

8. Writing and Reading Data from Firebase Firestore

We’ve already used Firestore above, for saving extra information on our users (the full name). In this dedicated section, we’re going to see how we can write data to Firestore, and how we can query it.

We’ll also cover how to observe (listen to) changes in the Firestore collection and have those be reflected on the screen, in real-time. These can be very helpful in real-time apps, such as a React Native Chat.

To simplify, we are going to save some text items into a Firestore collection named “entities”. Think of these as tasks, posts, tweets, anything you want. We’ll create a simple file that adds a new entity and we’ll also list all the entities that belong to the currently logged in user. Additionally, the list will be updated in real-time.

  • Implement HomeScreen.js by rewriting it to the code below
  • Style the home screen, by overriding HomeScreen/styles.js to:
  • Reload the app and observe the new home screen. Type in some text and press the Add button
  • Nothing happened.
  • Create an index on the entities Firestore collection

You’ll notice that the list of entities is not rendered. If you check out the logs, you’ll see an warning about “The query requires an index”, followed by a long URL:

This informs us that we can’t query the entities table by authorID and sort the data by createdAt in descending order, unless we create an index. Creating an index is actually really easy — simply click on that URL and then click the button:

  • Reload the app again

Now everything works as expected:

  • The app lists all the entities in the entities collection, in descending creation order
  • Adding a new entity works fine
  • The list updates in real-time (try deleting an entry directly in the database, or adding a new one directly from the app)

This is how your Firestore database looks like now:

This is how you read and write from Firestore in React Native. Let’s move forward to the last section.

Play around with the app, by adding new entities. This is the final project:

Conclusion

Firebase makes it really easy to add authentication and database support to any React Native app. Firebase SDK is extremely powerful, supporting a lot of common reading and writing database patterns.

In addition to React Native, Firebase SDK provides support for a lot of other languages, such as Swift, Kotlin or Flutter. Check out those links for similar Firebase starter kits in various languages.

We’ve showcased the most basic ones in this React Native Firebase tutorial. In the next series, we’ll cover more advanced features, such as Firebase Storage (file upload) and push notifications.

Kui teile see õpetus meeldis, siis andke mulle Githubi repos tärn ja jagage seda oma kogukonnaga. Instamobile'is saate vaadata veelgi rohkem tasuta React Native'i projekte. Terviseks!