Ionic 2 Firebase initializeApp & onAuthStateChanged slow - android

I'm working on my first Firebase app with Ionic and I'm having some issues with my login code. From my browser I see no issues but once I install the app on to a phone(iOS & Android) the login takes about a minute because the callback from onAuthStateChanged takes a long time. I'm using "firebase": "^3.8.0". I added the code I'm using to login. Any ideas on why Firebase is choking?
app.component.ts
constructor(public platform: Platform, private statusBar: StatusBar) {
this.rootPage = LoginPage;
let config = {
apiKey: "***",
authDomain: "***",
databaseURL: "***",
storageBucket: "***",
messagingSenderId: "***"
};
firebase.initializeApp(config);
this.authData = new AuthData();
this.zone = new NgZone({});
const subscribe = firebase.auth().onAuthStateChanged((user) => {
console.log("onAuthStateChanged");
this.zone.run(() => {
console.log(" zone onAuthStateChanged");
if (!user) {
this.rootPage = LoginPage;
subscribe();
} else {
// this.rootPage = HomePage;
this.rootPage = EditProfile;
subscribe();
}
});
});

Upgrading to firebase 3.9.0 in your project, solves the issue for sure.

I also faced with the same issue.
After some research I found that this issue comes with firebase "3.8.0".
Downgrade to 3.6.6 solved the problem for me

The update 3.8.0 slowed down the authentication on Ionic 2 devices. Here is the discussion about it in this issue and the solution by the firebase team untill they fix it google docs in the new patch.

Related

Unable to resolve "idb" from "node_modules\#firebase\app\dist\esm\index.esm2017.js"

i am facing a problem since past days, and not able to solve it
can anyone help me slight to make it work efficiently
Moreover also have degraded firebase to 9.6.11 as per other solutions on similar site.
import firebase from "firebase/compat/app";
import "firebase/compat/auth";
import "firebase/compat/firestore";
// Your web app's Firebase configuration
const firebaseConfig = {
apiKey: ".......................",
authDomain: ".......................",
projectId: ".......................",
storageBucket: ".......................",
messagingSenderId: ".......................",
appId: "......................."
};
// Initialize Firebase
let app;
if (firebase.apps.length === 0) {
app = firebase.initializeApp(firebaseConfig);
} else {
app = firebase.app()
}
const auth = firebase.auth()
export { auth };````
the issue is solved
thanks.
Create a new file metro.config.js in the root folder of your project and add the code snippet in it.
const { getDefaultConfig } = require("#expo/metro-config");
const defaultConfig = getDefaultConfig(__dirname);
defaultConfig.resolver.assetExts.push("cjs");
module.exports = defaultConfig;
there's an issue open on the metro repo facebook/metro#535
builds work fine again for me after adding this to my metro config:
resolver: {
sourceExts: ['js', 'json', 'ts', 'tsx', 'cjs'],
},
Though the most upper one resolve the issue. If you want to know more, follow this official link - https://docs.expo.dev/guides/using-firebase/#step-3-configure-metro
Or just paste the code in a new file metro.config.js on your root project folder -
const { getDefaultConfig } = require('#expo/metro-config');
const defaultConfig = getDefaultConfig(__dirname);
defaultConfig.resolver.assetExts.push('cjs');
module.exports = defaultConfig;

React Native repeated timeouts writing collection to firestore#firebase/firestore: Firestore (8.4.2): Connection WebChannel transport errored

I am trying to write a user to a firestore collection from a react native app. The user gets created in firebase fine under authentication but it then hangs on the firebase.firestore().collection('users').doc(uid).set('data').
After a few minutes I get a warning: "firestore#firebase/firestore: Firestore (8.4.2): Connection WebChannel transport errored"
I will continue getting this warning every few minutes and sometimes after 20 mins or so the collection might be written to firestore.
There are a few questions in the github and on SO with this issue but none have a fix. Any one come across this?
My code
import '#firebase/auth';
import '#firebase/firestore';
const firebaseConfig = {
apiKey: "xxxxxxxxxxxxxxxxxxx",
authDomain: "xxxxxxxxxxxx",
projectId: "xxxxxxxxx",
storageBucket: "xxxxxxxxxxxxxxx",
messagingSenderId: "xxxxxxxxxxxxxx",
appId: "xxxxxxxxxxxx",
measurementId: "xxxxxxxxxxxxx"
};
if (!firebase.apps.length) {
firebase.initializeApp(firebaseConfig);
}
export { firebase };
import { StatusBar } from 'expo-status-bar';
import React from 'react';
import { StyleSheet, Text, View, Button } from 'react-native';
import { firebase } from '../src/firebase'
const handleSubmit = (email,password) => {
console.log(email + password);
firebase
.auth()
.createUserWithEmailAndPassword(email, password)
.then((response) => {
const uid = response.user.uid
const data = {
id: uid,
email
};
const usersRef = firebase.firestore().collection('users')
usersRef
.doc(uid)
.set(data)
.then(() => {
console.log('please get here')
})
.catch((error) => {
console.log('error get here')
});
})
.catch((error) => {
console.log('outer error get here ' + error)
});
}
export default function App() {
return (
<View style={styles.container}>
<Button
onPress={handleSubmit('f#d.com', 'pass123')}
title='test'
/>
<StatusBar style="auto" />
</View>
);
}
const styles = StyleSheet.create({
container: {
flex: 1,
backgroundColor: '#fff',
alignItems: 'center',
justifyContent: 'center',
},
});
So I asked this question on the firebase github, see: https://github.com/firebase/firebase-js-sdk/issues/4859
The solution they gave worked for me which was to add the below code when initializing firebase.
firebase.initializeApp(firebaseConfig);
firebase.firestore().settings({ experimentalForceLongPolling: true });
In case it helps anyone, a more recent fix that worked for me was
import {initializeFirestore} from 'firebase/firestore'
const db = initializeFirestore(firebaseApp, {useFetchStreams: false})
Quoting the team:
"The issue is caused by useFetchStreams being enabled by default, in the new modular build (v9). Since RN does not fully support fetch readable streams, projects have to fall back to XHR (which was the default in v8)."
They also say the fetch fix for RN should be released this week.
The thread is here:
https://github.com/firebase/firebase-js-sdk/issues/5667
Your error message indicates that you are using Firebase SDK v8.4.2. However, that is newer than the current version supported by the Expo SDK.
When installing dependencies under expo, be sure to install them via expo install firebase and not npm install firebase.
To be sure you have the correct version installed right now, do:
npm uninstall firebase
expo install firebase
Then try running your app again.

Expo React Native google auth with firebase not working in published apk version on android

I wanted to include google Auth in my app but it is not working in the published version on android even though it worked with expo
Here is the code:
logInGoogle = async () => {
try {
const result = await Google.logInAsync({
androidClientId:ID,
iosClientId:ID,
scopes: ["profile", "email"],
behavior:'web'
});
if (result.type === "success") {
const { idToken, accessToken } = result;
const credential = GoogleProvider.credential(idToken, accessToken);
Firebase
.auth()
.signInWithCredential(credential)
.then(function(result){
if(result.additionalUserInfo.isNewUser){
Firebase.database().ref('UserToQuestion/' + Firebase.auth().currentUser.uid).set({
notifier: {
Email:Firebase.auth().currentUser.email
}
})
}
})
.catch(error => {
Alert.alert(error)
console.log("firebase cred err:", error);
});
} else {
return { cancelled: true };
}
} catch (err) {
console.log("err:", err);
}
}
Here is my app.json for android
"android": {
"package": "com.aparson.SFS",
"versionCode": 1
},
In the google console, I have a working service account but I have not configured the OAuth consent screen, but I am not sure if that is the problem because when I click the button for google login nothing happens at all. I have also changed the SHA-1 certificate to what the app signing showed which is what someone said to do in a different question but that did not work either.
I would appreciate it if anyone could help.
Thanks
you should use expo-google-sign-in
expo-google-sign-in provides native Google authentication for standalone Expo apps or bare React Native apps. It cannot be used in the Expo client as the native GoogleSignIn library expects your REVERSE_CLIENT_ID in the info.plist at build-time. To use Google authentication in the Expo client, check out expo-google-app-auth or expo-app-auth.
https://docs.expo.io/versions/latest/sdk/google-sign-in/#googleidentity

React-Native: "FirebaseError: No Firebase App '[DEFAULT]' has been created - call Firebase App.initializeApp() (app/no-app)"

I'm building a React Native app, currently trying to implement an authentication registration system through Firebase Auth. I've followed a guide/the docs on the website to setup the Firebase config file. I run the app, enter a email and password, when I click the signup button I'm given the follow error below:
FirebaseError: Firebase: No Firebase App '[DEFAULT]' has been created - call Firebase App.initializeApp() (app/no-app).
I've search on google for possible fixes yet nothing seems to work. I've initialized Firebase as per the docs/tutorials I've watched. Hopefully someone can shed some light on the matter. I'll include the config file code below, XXXX to replace my actual config info
firebase.js
import * as firebase from 'firebase/app';
import "firebase/auth";
const firebaseConfig = {
apiKey: "XXXX",
authDomain: "XXXX",
databaseURL: "XXXX",
projectId: "XXXX",
storageBucket: "XXXX",
messagingSenderId: "XXXX",
appId: "XXXX",
measurementId: "XXXX"
};
firebase.initializeApp(firebaseConfig);
api.js
export function registerUser({email, password}) {
firebase
.auth()
.createUserWithEmailAndPassword(email, password)
.catch(function(error) {
console.log(error);
});
};
EDIT/ANSWER
As helped in the comments below, the correct way was to implement/import through React-Native-Firebase. Links are in the comments.
Seemingly you are using the syntax of Invertase Firebase project while on the back you are using the WEB SDK of firebase from a firebase npm package.
here is what you should do:
go and install react-native-firebase from here
make sure the pods work and auto-linking works, you have included the json and plist file.! only following these your projects will build and you can use the syntax you have posted in your question!
You Write Your configuration Like Follow:
componetWillMount() {
const config = {
apiKey: “xxxxxxxxxxxxxxxxxxxxxxxx”,
authDomain: “auth-bdcdc.firebaseapp.com 20”,
databaseURL: “https://auth-bdcdc.firebaseio.com 7”,
projectId: “auth-bdcdc”,
storageBucket: “auth-bdcdc.appspot.com 2”,
messagingSenderId: “xxxxxxxxxx”
};
firebase.initializeApp(firebaseConfig);
}
Check if GoogleService-Info.plist is missing in the ios folder.
This is what I did to solve it.
Use Async function for the registrations
FirebaseConfig.js
import firebase from 'firebase/app';
const firebaseConfig = {
apiKey: "XXXX",
authDomain: "XXXX",
databaseURL: "XXXX",
projectId: "XXXX",
storageBucket: "XXXX",
messagingSenderId: "XXXX",
appId: "XXXX",
measurementId: "XXXX"
};
firebase.initializeApp(firebaseConfig); // It's expecting an objects
Registration as async function:
Registration.js
export async function Registration(email, password, lastName, firstName) {
try {
await firebase.auth().createUserWithEmailAndPassword(email, password);
const currentUser = firebase.auth().currentUser;
const db = firebase.firestore();
db.collection("users").doc(currentUser.uid).set({
email: currentUser.email,
lastName: lastName,
firstName: firstName,
});
} catch (err) {
Alert.alert("There is something wrong!!!!", err.message);
}
}
If those works don't forget to upvote.
I think need to put below setup in AppDelegate.m file ...
#import <Firebase.h>
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
{
[FIRApp configure];
}

Error handling on react-native-fcm

I'm integrating FCM on my react-native application using https://github.com/evollu/react-native-fcm.
The notification works but I got this error every time.
console.error: "Notification handler err", {"line":67974,"column":14,"sourceURL":"http://localhost:8081/index.android.bundle?platform=android&dev=true&hot=false&minify=false"}
Environment:
react-native-cli: 2.0.1
react-native: 0.40.0
react-native-fcm: 6.1.0
I'm testing on Android ver 6.0.1 and the app is running in foreground.
I removed old code Firebase initialisation code on index.js, and it caused the error.
firebase.initializeApp({
apiKey: "",
authDomain: "",
databaseURL: "",
storageBucket: ""
});
I removed it and it's working now.
For react-native fcm. See object aps.alert
FCM.on("FCMNotificationReceived", (notification) => {
if (Platform.OS === 'ios') {
if (notification && notification.aps) {
const localNotification = {
title: notification.aps.alert.title,
body: notification.aps.alert.body,
show_in_foreground: true,
}
FCM.presentLocalNotification(localNotification);
}
}
});
FCM.on("FCMNotificationReceived", (notification) => {
// Also trigged when FCM.presentLocalNotification() and callback a notification without **aps** object;
// So the app crash, error
// Just check if (notification && notification.aps) and make localNotification object like above code
})

Categories

Resources