I am new to React Native and still learning. Everything was working well but suddenly I got and error in the emulator and also in code editor and spent two days trying to find a solution but found nothing
I am getting two errors
1) In code editor (unreachable code ts.7027
2) In emulator (the development server returned response error code : 500)
I tried a lot to change and revise the code may be some syntax error or even spelling but I couldn't
This is for new react-native project
This of creating Login page form
import React, { Component } from 'react';
import {View} from 'react-native';
import firebase from 'firebase';
import {Header, Button, Spinner} from './Components/Common';
import LoginForm from './Components/LoginForm';
class App extends Component {
state = { loggedIn: null };
componentWillMount () {
firebase.initializeApp(
{
apiKey: "AIzaSyAX09VgJkSzx3d5z8UcyznmhTUNLUgYzMw",
authDomain: "hatimauth.firebaseapp.com",
databaseURL: "https://hatimauth.firebaseio.com",
projectId: "hatimauth",
storageBucket: "",
messagingSenderId: "62394723382",
appId: "1:62394723382:web:bd5e4bb7a365a05b"
});
firebase.auth().onAuthStateChanged((user) => {
if (user) {
this.setState({loggedIn: true});
}else {
this.setState({loggedIn: false });
}
});
renderContent () {
switch (this.state.loggedIn) {
case true:
return (
<Button onPress{()=> firebase.auth().signOut()}> Log Out
</Button>
);
case false:
return <LoginForm/>;
default:
return <Spinner size='large'/>;
}
}
render () {
return (
<View>
<Header headerText='Authentication'/>
{this.renderContent}
</View>
)
};
export default App;
Expected to run normally especially that it's run normally through the course video
The course is udemy react-native and redux full course
You are missing the closing bracket on the componentWillMount. I would recommend downloading a linter, something like prettier for your IDE.
componentWillMount () {
firebase.initializeApp(
{
apiKey: "AIzaSyAX09VgJkSzx3d5z8UcyznmhTUNLUgYzMw",
authDomain: "hatimauth.firebaseapp.com",
databaseURL: "https://hatimauth.firebaseio.com",
projectId: "hatimauth",
storageBucket: "",
messagingSenderId: "62394723382",
appId: "1:62394723382:web:bd5e4bb7a365a05b"
});
firebase.auth().onAuthStateChanged((user) => {
if (user) {
this.setState({loggedIn: true});
}else {
this.setState({loggedIn: false });
}
});
}
Additionally, I would recommend learning how to work with .env files and put them in a git ignore so that you aren't sharing your API key with the world (sharing a good package to look through):
https://github.com/luggit/react-native-config
Related
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;
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.
Initial Situation:
I need to implement a Google login with Ionic which works on a web platform as well as on an android device.
Therefore I use:
Ionic 5.2.2
Capacitor 1.1.1
Capacitor OAuth 2 client plugin 1.0.0
With that setup I achieved already:
Web-Login workes perfectly
Problem:
Login in from an Android device doesn't work
I followed the steps in the readme from https://github.com/moberwasserlechner/capacitor-oauth2/blob/master/README.md
I registered the plugin OAuth2Client in my app.component.ts
I implemented a method googleLogin() where I call Plugins.OAuth2Client.authenticate() with OAuth2AuthenticateOptions
app.component.ts
import { Component, OnInit } from '#angular/core';
import { registerWebPlugin } from "#capacitor/core";
import { OAuth2Client } from '#byteowls/capacitor-oauth2';
#Component({
selector: 'app-root',
templateUrl: 'app.component.html'
})
export class AppComponent implements OnInit {
constructor() {}
ngOnInit() {
console.log("Register custom capacitor plugins");
registerWebPlugin(OAuth2Client);
}
}
home.page.ts
import { Component } from '#angular/core';
import { Plugins } from '#capacitor/core';
#Component({
selector: 'app-home',
templateUrl: 'home.page.html',
styleUrls: ['home.page.scss'],
})
export class HomePage {
constructor() { }
async googleLogin() {
try {
const resourceUrlResponse = await Plugins.OAuth2Client.authenticate({
appId: "XXX.apps.googleusercontent.com",
authorizationBaseUrl: "https://accounts.google.com/o/oauth2/auth",
accessTokenEndpoint: "https://www.googleapis.com/oauth2/v4/token",
scope: "email profile",
resourceUrl: "https://www.googleapis.com/userinfo/v2/me",
web: {
redirectUrl: "http://localhost:8100",
windowOptions: "height=600,left=0,top=0"
},
android: {
appId: "XXX.apps.googleusercontent.com",
responseType: "code",
customScheme: "com.xxx.playground.googleLogin07"
}
})
}
catch (err) {
console.error(err);
}
}
}
On an device this code results in an error-message from Google:
enter image description here
This is plausible. It seems to be that the method Plugins.OAuth2Client.authenticate() tries to do a web-based login where an android login is needed. Am I right?
If I make a call without the "web"-parameter like this...
const resourceUrlResponse = await Plugins.OAuth2Client.authenticate({
appId: "XXX.apps.googleusercontent.com",
authorizationBaseUrl: "https://accounts.google.com/o/oauth2/auth",
accessTokenEndpoint: "https://www.googleapis.com/oauth2/v4/token",
scope: "email profile",
resourceUrl: "https://www.googleapis.com/userinfo/v2/me",
android: {
appId: "XXX.apps.googleusercontent.com", //--> I tried both, android- and web-client key from the google clout platform console.
responseType: "code",
customScheme: "com.xxx.playground.googleLogin07"
}
})
...the method Plugins.OAuth2Client.authenticate() returns a blank error object --> {}
What am I doing wrong?
I'm new to React Native and have the following problem:
I import firebase auth in such way...
import React, { Component } from 'react';
import { Text } from 'react-native';
import { Button, Card, CardSection, Input } from './common';
import { auth } from 'firebase';
I just import it in my component and use it on log in button press.
class LoginForm extends Component {
state = { email: '', password: '', error: '' };
onButtonPress() {
debugger;
const { email, password } = this.state;
auth.auth().signInWithEmailAndPassword(email, password)
.catch(() => {
auth.auth().createUserWithEmailAndPassword(email, password)
.catch(() => {
this.setState({ error: "Authentication failed." });
});
});
debugger;
}
My App module looks like this...Here I make some initialization for my app
import firebase from '#firebase/app';
import LoginForm from './components/LoginForm'
Here I make some initialization for my app
componentWillMount() {
debugger;
firebase.initializeApp({
apiKey: 'somekey',
authDomain: 'somedomain',
databaseURL: 'someurl',
projectId: 'someid',
storageBucket: 'authentication-afcb6.appspot.com',
messagingSenderId: '253116783153'
});
debugger;
}
But my emulator shows me an error:
The problem is with your import statement I suppose. When using firebase I always used:
import firebase from 'firebase';
firebase.auth().<METHOD>
Or I think you could also import it like this if it's a named export and use it directly:
import {auth} from 'firebase';
auth().<METHOD>
Also hopefully you do know that you have to initialize your app as well using firebase.initializeApp({<CONFIG_DATA>}).
I suggest using react-native-firebase library. It uses native Android and iOS SDK under the hood, instead web javascript library.
Documentation
https://rnfirebase.io/docs/v5.x.x/installation/initial-setup
Android installation https://rnfirebase.io/docs/v5.x.x/installation/android
iOS installation https://rnfirebase.io/docs/v5.x.x/installation/ios
What is the version of firebase you are using?
Downgrading firebase to 5.0.3 is the only solution I find and I just tried myself and it works. For reference, here is the thread on firebase-js-sdk.
I am building an app that is using Google authentication through firebase and that needs to redirect the user from a login.vue component to an /hello path upon successful authentication.
I have first tried doing it the normal vue way:
this.$router.replace('/hello')
only to realise my Samsung Galaxy J5 wasn't having it...
All is working on other devices and browsers (so far) using the normal Vue routing tools but on some Android devices Vue is refusing to collaborate. I have read here some Android versions do not like the way the Vue dynamic routing transpiles to vanilla JS so I am attempting the following (still, no success).
This is my code on the created hook of component login.vue when Google auth (with redirection, not pop up) returns to it:
created() {
firebase.auth().getRedirectResult().then(result => {
var user = result.user;
if (user) {
var ua = navigator.userAgent.toLowerCase();
var isAndroid = ua.indexOf("android") > -1;
if(isAndroid) { // NOT WORKING (stays on Login.vue although I am sure it's detecting it's an Android)
window.location.href = window.location.host + '/hello';
} else {
this.$router.replace('/hello') // this work perfectly
console.log(window.location.host + "/hello" ); // this is returning the intended address: localhost:8080/hello
}
} else {
toastr.warning("Oops something went wrong on login!");
}
}).catch(error => {
// dealing with redirection result errors from Google Authentication
});
This is my index.js routing file (I am doing some route guarding here so it may be useful for you to get a bigger picture if I paste the file):
import Vue from 'vue'
import Router from 'vue-router'
import firebase from '../firebase-config'
import {store} from '#/store/store'
import hello from '#/components/hello'
import login from '#/components/login'
import landing from '#/components/landing'
Vue.use(Router)
let router = new Router({
mode: 'history',
routes: [
{
path: '*',
redirect: '/landing'
},
{
path: '/',
redirect: '/landing'
},
{
path: '/landing',
name: 'landing',
component: landing
},
{
path: '/login',
name: 'login',
component: login
},
{
path: '/hello',
name: 'hello',
component: hello,
meta: {
requiresAuth: true
}
},
],
})
router.beforeEach((to, from, next) => {
if (to.matched.some(record => record.meta.requiresAuth)) {
firebase.auth().onAuthStateChanged(function(user) {
if (!user) {
next({
path: '/landing'
})
} else {
next()
}
});
} else {
next()
}
})
export default router
Any thoughts?