install react native firebase
npm install --save @react-native-firebase/app
Now we have to add some dependencies in the android folder
To allow Firebase on Android to use the credentials, theÂ
google-services
 plugin must be enabled on the project. This requires modification to two files in the Android directory.First, add theÂ
google-services
 plugin as a dependency inside of your /android/build.gradle
 file:buildscript { dependencies { // ... other dependencies classpath 'com.google.gms:google-services:4.3.14' // Add me --- /\ } }
Lastly, execute the plugin by adding the following to yourÂ
/android/app/build.gradle
 file:apply plugin: 'com.google.gms.google-services' // <- Add this line
Method 2
npm install firebase
first you go to firebase website
then create new project
then select to use the project in web app
then it will give you one cofig file
then copy this file and paste in →firebase.config.js
firebase.config.js
make one file firebase.config.js and add this code
import { initializeApp } from 'firebase/app'; import { getDatabase } from 'firebase/database'; const firebaseConfig = { apiKey: "fsdvsdfvsdfhtrsyrtfdvdsfvsdfg", authDomain: " something.com", databaseURL: " ", projectId: " ", storageBucket: "kmkdsamlmkmakd.com", messagingSenderId: "234234234234", appId: "asdfasdfasdafsdf", measurementId: "sadfasdfdsfddf" }; const app = initializeApp(firebaseConfig); const db = getDatabase(app); export { db };
Now this db start to create and delete the data
You need to craete the realtime database iin firebase website
app.js
import db and some methods from firebase
import { db } from '../../firebase/firebase.config'; import { ref, onValue, push, update, remove, set } from 'firebase/database';
now we’ll push the data or update the data ( set ) from our application
DemoToDo.js
import React,{useState} from 'react'; import {View, StyleSheet,Button, TextInput} from 'react-native'; import { db } from '../../firebase/firebase.config'; import { ref, onValue, push, update, remove, set } from 'firebase/database'; const DemoToDo = () => { const [todo, setTodo] = useState(''); const addNewTodo=()=> { // set(ref(db, 'ToDo/'+"aksdhjfhjk"), { // text: todo, // }); // console.log("run") push(ref(db, '/ToDo'), { text: todo, }); setTodo(''); } return ( <View> <TextInput className="border-2 rounded-sm my-5 mx-2 p-3" placeholder='ToDo' onChangeText={(text) => { console.log("text :", text); setTodo(text) }} value={ todo} /> <Button title="Add" onPress={addNewTodo} /> </View> ); } const styles = StyleSheet.create({}) export default DemoToDo;
Write data
Read Data
const [listTodos, setlistTodos] = useState([]);// setting the list useEffect(() => { return onValue(ref(db, '/ToDo'), querySnapShot => { let data = querySnapShot.val() || {}; // console.log("data : ", data); let todoItems = {...data}; setlistTodos(todoItems); }); }, []);
data will be in the default object format so not in array so that we have to extract the key values and then render the text
const todosKeys = Object.keys(listTodos);
render the element
{ todosKeys.map( (item,key) => { return ( <View className="bg-gray-200 p-3 my-1 rounded-md mx-2 border " key={key}> <Text className="text-green-900" >{listTodos[item].text }</Text> </View> ) } ) }
Authentication
import { getAuth } from "firebase/auth"; const auth = getAuth(); // default language firebase.auth().useDeviceLanguage();
Now if this is Login page then add {signInWithEmailAndPassword} from “firebase/auth” ;
and set the state of email and password
import { app } from '../../firebase/firebase.config'; const auth = getAuth(app); const SignIn = () => { signInWithEmailAndPassword(auth,email,password).then((userCredential) => {console.log("success : ",userCredential);alert("Success")}).catch((error) => {console.log(error);alert("Error")}); }
Google Signin
problem
whenever you want to extract message from firebase error then if you print in the console it will simply show you [FirebaseError: Firebase: Error (auth/email-already-in-use).]
But if you want to show the same message in some dialogue box then you simply log the JSON.stringify(error) it will show you whole object with its property {"code":"auth/email-already-in-use","customData":{"appName":"[DEFAULT]","_tokenResponse":{"error":{"code":400,"message":"EMAIL_EXISTS","errors":[{"message":"EMAIL_EXISTS","domain":"global","reason":"invalid"}]}}},"name":"FirebaseError"}
Now we simply use the property to show the error
Â
Session
in web(React.sj )
in web all the steps are same except gettung the email every time we refresh the page for that we have to import a fucntion from firebase/aut library called AuthStatechanged
Then we have maintain the state called user so that we save the user data in that . It will be an object
const [user, setUser] = useState({}); anAuthStateChangedlauth, (currentUser => setUser(currentUser); });
To logout import signOut from firebase/auth library then simply call signOut(auth) in that function
after that the currentUser will set to null object so set any text or condition keeping this in mind
Session → when we login through firebase we can get every info in auth.currentUser object
like → email , name , UID and all
at any page we can access
Store
import { configureStore, createSlice } from "@reduxjs/toolkit"; const initialState = { data: [{"creaditedAmount":"1000"}] }; const creditedData = createSlice({ name: "creditedData", initialState, reducers:{ setdata: (state, action) => void(state.data = action.payload), } }); // user const userInitialState = { UserData:[{ "name": "", "email": "", "phone": "", "password": "" ,"islogin":false}] }; const user = createSlice({ name: "user", initialState: userInitialState, reducers: { setUserData: (state, action) => void (state.UserData = action.payload), } }); const store = configureStore({ reducer: { creditedData: creditedData.reducer ,user:user.reducer} }); export const { setdata } = creditedData.actions; export const { setUserData } = user.actions; export default store;
SignOut and Verification
import React,{useState} from 'react'; import {View, StyleSheet, Button, Text} from 'react-native'; const { initializeAppCheck, ReCaptchaV3Provider } = require("firebase/app-check"); import { app } from '../../firebase/firebase.config'; import { getAuth, signOut } from 'firebase/auth'; import { useSelector, useDispatch } from 'react-redux'; import { setUserData } from '../../store/store'; const auth = getAuth(app); const RecapthaScreen = () => { const [text, settext] = useState('') const dispatch= useDispatch(); const user = useSelector(store => store.user.UserData); // console.log(user); const handleSignOut = () => { signOut(auth).then(() => { // Sign-out successful. console.log('signed out'); dispatch(setUserData({email:'',islogin:false})); }).catch((error) => { // An error happened. console.log(error); }); } return ( <View className="flex flex-col space-y-4 w-full min-h-screen justify-center items-center bg-black"> <Text className="dark:text-gray-200 ">{user.islogin?user.email:"Not Logged in"}</Text> <Button title="Sign Out" onPress={handleSignOut}/> </View> ); } const styles = StyleSheet.create({}) export default RecapthaScreen;
Login and set state
import React,{useState} from 'react'; import {View, StyleSheet,Text,KeyboardAvoidingView,TextInput, Button,TouchableOpacity,Image} from 'react-native'; import { getAuth, RecaptchaVerifier, signInWithPhoneNumber,GoogleAuthProvider,createUserWithEmailAndPassword,signInWithEmailAndPassword } from "firebase/auth"; import { app } from '../../firebase/firebase.config'; const auth = getAuth(app); // modal import { Modal, SlideAnimation, ModalContent } from 'react-native-modals'; import { useDispatch } from 'react-redux'; import { setUserData } from '../../store/store'; // modal // createUserWithEmailAndPassword(auth, "harshitlove28@gmail.com", "123456").then((userCredential) => {console.log(userCredential);}).catch((error) => {console.log(error);}); const AuthScreen = ({ navigation }) => { const dispatch=useDispatch(); const [email, setemail] = useState(''); const [password, setpassword] = useState(''); const [confpassword, setconfpassword] = useState(''); const [modalContent, setmodalContent] = useState(''); const [modalVisible, setmodalVisible] = useState(false); // console.log(auth); const SignIn = () => { if (password === "" || email === "" ) { setmodalContent("Please fill all the fields"); setmodalVisible(true); return; } signInWithEmailAndPassword(auth, email, password).then((userCredential) => { console.log("success : ", userCredential); alert("Success"); dispatch(setUserData({email:email,islogin:true})); }).catch((error) => { console.log(error); alert("Error") }); } return ( <View className="bg-gray-200 dark:bg-gray-900 min-h-screen"> <View className="logo w-full h-3 top-[10%]"> <Image source={require('../../assests/logo.png')} className="w-20 h-20 mx-auto"/> </View> <View className="flex flex-row justify-center items-center max-h-full min-h-[70%]"> <KeyboardAvoidingView className="w-full"> <TextInput placeholderTextColor="gray" className="dark:text-gray-200 border border-gray-400 rounded-md px-5 mx-2 py-2 my-2 " placeholder="email" value={email} onChangeText={(text) => setemail(text)} /> <TextInput placeholderTextColor="gray" className="dark:text-gray-200 border border-gray-400 rounded-md px-5 mx-2 py-2 my-2 " placeholder="Password" value={password} secureTextEntry={true} onChangeText={(text) => setpassword(text)} /> <TouchableOpacity className="mx-2 bg-green-700 px-1 py-2 rounded-md" title='' onPress={SignIn} ><Text className="text-white text-center">Sign In</Text></TouchableOpacity> <TouchableOpacity className="mx-2 px-1 py-2 rounded-md" title='' onPress={() => { navigation.navigate('register'); }} ><Text className="text-blue-600 text-center text-xs dark:text-gray-300">Not a member?Register here</Text></TouchableOpacity> </KeyboardAvoidingView> </View> <Modal visible={modalVisible} onTouchOutside={() => { setmodalVisible(false); }} modalAnimation={new SlideAnimation({ slideFrom: 'bottom', })} > <ModalContent> { <View className="p-2"> <Text className="text-center text-xl text-black">{modalContent}</Text> <Text className="text-xs text-center">Please fill correct information to proceed!!</Text> <TouchableOpacity className=" flex flex-row w-[90%] mt-10 justify-end " onPress={()=>{setmodalVisible(false)}}><Text className="bg-red-500 p-2 text-white rounded-lg ">Close</Text></TouchableOpacity> </View> } </ModalContent> </Modal> </View> ); } const styles = StyleSheet.create({}) export default AuthScreen;
Â
Â