Connect Firebase with React Native - firebase

I'm trying to connect React Native with Firebase. I'm using the following method to connect Firebase.
import * as firebase from 'firebase';
// Initialize Firebase
const firebaseConfig = {
apiKey: "<YOUR-API-KEY>",
authDomain: "<YOUR-AUTH-DOMAIN>",
databaseURL: "<YOUR-DATABASE-URL>",
storageBucket: "<YOUR-STORAGE-BUCKET>"
};
firebase.initializeApp(firebaseConfig);
app.authWithPassword({
"email": "abc#abc.com",
"password": "abc1234"
}, (error, user_data) => {
if (error) {
alert('Login Failed. Please try again');
} else {
AsyncStorage.setItem('user_data', JSON.stringify(user_data));
}
});
But it returns the following error:
app.authWithPassword is not a function.
I'm using Firebase 3.4 and React Native 0.32.

From the Firebase documentation:
firebase.auth().signInWithEmailAndPassword(email, password).catch(function(error) {
// Handle Errors here.
var errorCode = error.code;
var errorMessage = error.message;
// ...
});

Related

Please be sure to call `initializeAuth` or `getAuth` before starting any other Firebase SDK. [Firebase Auth on NextJS App]

I'm trying to deploy my NextJS App on Vercel. But I'm getting this error.
Also, my project runs smoothly in development mode, but why am I getting such an error while deploying?
Firebase.ts File
import { initializeApp } from "firebase/app";
import {
getAuth,
signInWithEmailAndPassword,
onAuthStateChanged,
signOut,
} from "firebase/auth";
import { handlerSetUser } from "./utils";
const firebaseConfig = {
apiKey: process.env.NEXT_PUBLIC_FIREBASE_API_KEY,
authDomain: process.env.NEXT_PUBLIC_FIREBASE_AUTH_DOMAIN,
projectId: process.env.NEXT_PUBLIC_FIREBASE_PROJECT_ID,
storageBucket: process.env.NEXT_PUBLIC_FIREBASE_STORAGE_BUCKET,
messagingSenderId: process.env.NEXT_PUBLIC_FIREBASE_MESSAGING_SENDER_ID,
appId: process.env.NEXT_PUBLIC_FIREBASE_APP_ID,
};
// Initialize Firebase
const app = initializeApp(firebaseConfig);
const auth = getAuth(app);
onAuthStateChanged(auth, (user: any) => {
if (user) {
handlerSetUser(user);
} else {
handlerSetUser(false);
}
});
export const login = async (email: any, password: any) => {
try {
const result = await signInWithEmailAndPassword(auth, email, password);
return result;
} catch (error: any) {
alert(error.message);
}
};
export const logout = async () => {
try {
await signOut(auth);
} catch (error: any) {
alert(error.message);
}
};
Vercel Deployment Error
_errorFactory: ErrorFactory {
service: 'auth',
serviceName: 'Firebase',
errors: {
'dependent-sdk-initialized-before-auth': 'Another Firebase SDK was initialized and is trying to use Auth before Auth is initialized. Please be sure to call `initializeAuth` or `getAuth` before starting any other Firebase SDK.'
}
},

How can I get a valid Firebase user JWT token

Given that I have a Firebase project, but no development environment that supports the Firebase SDK, how can I get a valid Firebase JWT for one of the users in the Firebase project? I am able to create cloud functions in the project, and I tried making a function for this (in TypeScript), but to no avail:
import * as functions from "firebase-functions";
import * as admin from "firebase-admin";
admin.initializeApp();
export const login = functions.https.onRequest((req, res) => {
const email: string = req.query.email || req.body.email;
const password: string = req.query.password || req.body.password;
admin.auth().signInWithEmailAndPassword(email, password);
admin.auth().currentUser.getIdToken(true).then((idToken: any) => {
functions.logger.info("token: " + idToken, {structuredData: true});
res.status(200).send(idToken);
}).catch((error: any) => {
functions.logger
.info("could not get token: " + error, {structuredData: true});
res.status(500).send(error);
});
});
This code wont deploy due to these errors:
Property 'signInWithEmailAndPassword' does not exist on type 'Auth'.
Property 'currentUser' does not exist on type 'Auth'.
Here's the JS script I got from a colleague for this:
// Import the functions you need from the SDKs you need
const { initializeApp } = require("firebase/app");
const { getAuth, signInWithEmailAndPassword } = require("firebase/auth");
// Your web app's Firebase configuration
// For Firebase JS SDK v7.20.0 and later, measurementId is optional
const firebaseConfig = {
apiKey: "API-key-here",
authDomain: "my-app.firebaseapp.com",
databaseURL: "https://my-app-default-rtdb.firebaseio.com",
projectId: "my-app",
storageBucket: "my-app.appspot.com",
messagingSenderId: "sender-id-here",
appId: "app-id-here",
measurementId: "measurement-id-here"
};
const app = initializeApp(firebaseConfig);
const auth = getAuth();
signInWithEmailAndPassword(auth, "user#example.com", "user-password-here")=
.then((userCredential) => {
console.log(userCredential.user.accessToken);
})
.catch((error) => {
console.log(error.message);
});

firebaseConfig.default.auth promise rejection error

I am trying to signup user with facebook but i am seeing very rigid error and it seems there is no solved help out there so i am asking again
thats my code
async function signInWithFacebook() {
// const appId = Expo.Constants.manifest.extra.facebook.appId;
Facebook.initializeAsync(appid)
const permissions = ['public_profile']; // Permissions required, consult Facebook docs
const {
type,
token,
} = await Facebook.logInWithReadPermissionsAsync(
{permissions}
);
if(type == "success"){
const credential = initFirebase.auth.FacebookAuthProvider.credential(token);
initFirebase.auth().signInWithCredential(credential)
.catch(err => {
console.log(err)
})
}
}
i am using appid in strings but i have not added it here hope you understand that.
and the error is this
this is my firebase config file code
import firebase from "firebase/app"
import "firebase/firestore"
import "firebase/auth"
// Your web app's Firebase configuration
var firebaseConfig = {
apiKey: "xxxxxxxx",
authDomain: "xxxxxx",
databaseURL: "xxxxxx",
projectId: "xxxx",
storageBucket: "xxxxx",
messagingSenderId: "xxxxx",
appId: "xxxxx"
};
// Initialize Firebase
const initFirebase = firebase.initializeApp(firebaseConfig);
export default initFirebase
variable values are hidden because of privacy .i worked with firestore and that worked but i am seeing issue with auth with facebook .
i am using react native , firebase , expo and not firebase sdk
You don't have to register a Facebook App for Login with Facebook using Firebase. You can use the below code with Firebase Facebook Authentication enabled in the console.
export const loginWithFacebook = (accessToken) => {
const credential = initFirebase.auth.FacebookAuthProvider.credential(accessToken);
return new Promise((resolve, _reject) => {
signInWithCredential(credential).then(response => {
resolve(response);
});
});
};

NextJS: Accessing Google Firestore data

So I'm not sure how to do this exactly. Here is what I have:
In my Index.js I have
Index.getInitialProps = async function () {
const firebase = require('firebase')
const firebaseConfig = {
apiKey: "examplezbxW_9nKoUjas",
authDomain: "example-prod.firebaseapp.com",
databaseURL: "https://example-prod.firebaseio.com",
projectId: "example-prod",
storageBucket: "example-prod.appspot.com",
messagingSenderId: "1234567890",
appId: "1:1234567890:web:1234567890"
};
if (!firebase.apps.length) {
firebase.initializeApp(firebaseConfig)
}
const db = firebase.firestore()
const data = db.collection('data').get()
return {
data
}
}
This gives me an error of FirebaseError: projectId must be a string in FirebaseApp.options
(Maybe I need to run the firebase node package and login...)
It says the error is occurring at this line const db = firebase.firestore()
Any help is appreciated. Maybe this isn't the spot I should be trying to load firestore data... not sure.
I also considered creating a node server and doing it that way, but ideally, I'd like to avoid that.
Okay, so there was a couple changes I made to fix this.
I moved my firebase initialization to another file and that file looked like this:
import firebase from 'firebase/app'
import 'firebase/firestore'
export function loadDB() {
try {
var config = {
apiKey: "YOUR INFO HERE",
authDomain: "YOUR INFO HERE.firebaseapp.com",
databaseURL: "https://YOUR INFO HERE.firebaseio.com",
projectId: "YOUR INFO HERE",
storageBucket: "YOUR INFO HERE.appspot.com",
messagingSenderId: "YOUR INFO HERE",
appId: "YOUR INFO HERE"
};
firebase.initializeApp(config);
} catch (err) {
// we skip the "already exists" message which is
// not an actual error when we're hot-reloading
if (!/already exists/.test(err.message)) {
console.error('Firebase initialization error', err.stack);
}
}
return firebase;
}
Then, in my NextJS componenet, in the getInitialProps method, I have:
import { loadDB } from '../lib/db'
Index.getInitialProps = async function () {
const db = await loadDB()
let data = []
const querySnapshot = await db.firestore().collection('data').get()
querySnapshot.forEach(doc => {
data.push(doc.data())
})
return {
data
}
}

bundling failed: SyntaxError: Unexpected end of JSON input in react native

i am using firebase in my react native project. when i am try to sign up user with email and password this error is comming.
i am using window OS and only andorid render
Note: i had read all questions related to this but nothing helped
newbiew to react native .please guide in proper way
package.json
"firebase": "^5.8.2",
"native-base": "^2.11.0",
"react": "16.6.3",
"react-native": "^0.57.8",
"react-native-elements": "^0.19.1",
"react-native-firebase": "^5.2.2",
"react-native-gesture-handler": "^1.0.15",
"react-native-maps": "^0.23.0",
"react-native-svg": "^8.0.10",
"react-native-vector-icons": "^6.2.0",
"react-navigation": "^3.2.1"
Code for sign up
import * as firebase from 'firebase'
//Intiazlize firebase
const firebaseConfig = {
apiKey: "AIzaSyCUK5QkcvTcvfCKlbwnnI8GskIgcLGMcqA",
authDomain: "trailertracker-da09c.firebaseapp.com",
databaseURL: "https://trailertracker-da09c.firebaseio.com",
projectId: "trailertracker-da09c",
storageBucket: "",
}
firebase.initializeApp(firebaseConfig)
signUpUser = (email,password) => {
try{
if(this.state.password.length < 6 ){
alert("Please Enter Valid Email and Password")
return
}
firebase.auth().createUserWithEmailAndPassword(email,password)
} catch(err){
console.log(err)
}
}
Complete error is
Loading dependency graph, done. error: bundling failed: SyntaxError:
Unexpected end of JSON input
at JSON.parse ()
at FileStore.get (F:\React Native\ReactProjects\trailer-tracker\TrailerTracker\node_modules\metro-cache\src\stores\FileStore.js:26:19)
at F:\React Native\ReactProjects\trailer-tracker\TrailerTracker\node_modules\metro-cache\src\Cache.js:76:40
at Generator.next ()
at step (F:\React Native\ReactProjects\trailer-tracker\TrailerTracker\node_modules\metro-cache\src\Cache.js:18:30)
at F:\React Native\ReactProjects\trailer-tracker\TrailerTracker\node_modules\metro-cache\src\Cache.js:37:14
at new Promise ()
at F:\React Native\ReactProjects\trailer-tracker\TrailerTracker\node_modules\metro-cache\src\Cache.js:15:12
at Cache.get (F:\React Native\ReactProjects\trailer-tracker\TrailerTracker\node_modules\metro-cache\src\Cache.js:102:7)
at F:\React Native\ReactProjects\trailer-tracker\TrailerTracker\node_modules\metro\src\DeltaBundler\Transformer.js:166:34
BUNDLE [android, dev] ....../index.js 68.2% (947/1147), failed.
is this another error or error in firebase ?
Help will be highly appreciated
Thanks
To get started with firebase in react native.
add firebase dependency
yarn add firebase
Goto Firebase and make a new project and going to the section
Add Firebase to your web app
Make a class for configation of Firebase like this
import firebase from "#firebase/app";
require("firebase/database");
require("firebase/storage");
require("firebase/auth");
let config = {
apiKey: "YOUR PROJECT apiKey",
authDomain: "YOUR PROJECT authDomain",
databaseURL: "YOUR PROJECT databaseURL",
projectId: "XXXXXXXX",
storageBucket: "",
messagingSenderId: "XXXXXXXXXX",
appId: "XXXXXXXXXXXXXXXXXXXXXXXX"
};
export default class DBHandler {
static auth;
static database;
static init() {
firebase.initializeApp(config);
DBHandler.database = firebase.database();
DBHandler.auth = firebase.auth();
}
}
in App.js initialize Firebase
import DBHanlder from "./src/api/constants";
export default class App extends Component {
componentDidMount = () => {
DBHanlder.init();
};
render() {
return <YourApp />;
}
}
Your're done with initialization part .now you can use for auth like below
import DBHandler from "../api/constants";
class Login extends Component {
signinUser = () => {
DBHandler.auth.signInWithEmailAndPassword(email, password)
.then(() => {
//Do what you want
})
.catch((error) => {
//handle error
var errorCode = error.code;
var errorMessage = error.message;
alert(errorMessage);
console.log("ERROR");
console.log(errorCode, errorMessage);
});
}
}}

Resources