In my previous post, we covered how to set up Firebase in your React Native CLI App.
Firebase Auth offers several authentication providers, including email/password, phone number authentication, Google sign-in, etc. For this series, we'll be using React Native Firebase for our project.
To keep things simple, we'll implement Anonymous Authentication in our app. Let's dive in!
Firebase Console
Activate Anonymous Authentication or your preferred authentication provider from your firebase console.
Installing the package
First, let's install the React Native Firebase Auth package along with the core app package:
Setting up Auth Functions
It's good practice to create utility functions for auth functions to use them everywhere.
Create a folder called Firebase in your root directory and create a new file auth.js.
Let's start with some basic functions we need.
Here's the code for Firebase/auth.js:
Separate Screens Based Authentication
I'm using React Navigation, with separate navigators for logged-in users (MainStackNavigator) and those who are not (AuthStackNavigator), but you may use the same navigation and keep screens separate instead.
Handling Authentication State
Let's open our App.tsx We set states for a user and initializing and a function for auth state changed:
Then, we'll use a useEffect hook to subscribe to authStateChanged event handler to track authentication state changes:
Finally, we can separate our login screens from home screens based on the user's state like this:
This ensures that users are directed to the appropriate screens based on their authentication status.
Here is complete code for App.tsx
Login Screen
In my LoginScreen.jsx, I'll use signInAnonymously function to sign in into HomeScreen.jsx. Here's the basic code for Login Screen:
On logging in, we'll be directly taken to our Home Screen. If you try to press back when logged in, you won't be able to go back to the login screens.
Here the basic code for HomeScreen.jsx:
That wraps up our implementation of a simple authentication flow into our app using Firebase Auth.
If you're eager to explore more authentication-related topics, drop a comment below!
Your feedback helps shape the content you want to see. Let's dive deeper into authentication together!