Can't import firebase auth android - android

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.

Related

database is not function in react native firebase

this question is not duplicate for firebase.database is not function.
I installed firebase and import as follow
import React, { Component } from 'react'
import { View } from 'react-native'
import Card from '../components/card'
import firebase from 'firebase/compat/app'
import database from 'firebase/compat/database'
export default class Home extends Component {
state = {
profileIndex: 0,
profiles: [],
}
UNSAFE_componentWillMount() {
firebase.database().ref().child('Users').once('value', (snap) => {
let profiles = []
snap.forEach((profile) => {
const {name, bio, birthday, id} = profile.val()
profiles.push({name, bio, birthday, id})
})
this.setState({profiles})
})
}
when not import this
import database from 'firebase/compat/database'
show error as
firebase.daatabase is not function
but when import this
import database from 'firebase/compat/database'
error is gone and work but actually database is not using in code
I want to know the solution for this
How can use this method
firebase.database()
what need to import in react native
thanks
https://rnfirebase.io/database/usage
Installation
#react-native-firebase/app
#react-native-firebase/database
pod install
cd ios/ && pod install && cd ..
import database from '#react-native-firebase/database';

Ionic native Ibeacon ReferenceError: device is not defined

TLDR: Ibeacon module example does not work
I have a small app in Ionic 5 using capacitor.
I want to use the Ibeacon library, but I get the error :
Ressource for the library is scarse and I have only found people having issue when the delegate is undefined causing the LocatonManager error here.
I also tried to look what is causing the error, apparently the device mentioned is part of the device library. So I check if the Ibeacon library properly import the device one and it does in node_modules\cordova-plugin-ibeacon\plugin.xml, like so :
<!-- Version is set to anything because the only feature we use is the device.platform property which was available
since forever. The added benefit is that we don't force the consumers of this plugin to use a certain version of
the device plugin. -->
<dependency id="cordova-plugin-device" version="*" />
My class is pretty much the example given in the Ibeacon page:
import { Component, OnInit } from '#angular/core';
import { IBeacon } from '#ionic-native/ibeacon/ngx';
import { Platform } from '#ionic/angular';
#Component({
selector: 'app-beacon',
templateUrl: './beacon.page.html',
styleUrls: ['./beacon.page.scss'],
})
export class BeaconPage implements OnInit {
public beacons: any[] = [];
constructor(
private ibeacon: IBeacon,
private platform: Platform,
private _utils: UtilsService
) {}
ngOnInit() {
console.log('ngOnInit');
if (!this.platform.is('android')) {
console.log('Beacon related activity only available on Android');
return;
}
// create a new delegate and register it with the native layer
let delegate = this.ibeacon.Delegate();
console.log('delegate :', delegate);
// Subscribe to some of the delegate's event handlers
delegate.didRangeBeaconsInRegion().subscribe(
(data) => console.log('didRangeBeaconsInRegion: ', data),
(error) => console.error()
);
delegate.didStartMonitoringForRegion().subscribe(
(data) => console.log('didStartMonitoringForRegion: ', data),
(error) => console.error()
);
delegate.didEnterRegion().subscribe((data) => {
console.log('didEnterRegion: ', data);
});
let beaconRegion = this.ibeacon.BeaconRegion(
'deskBeacon',
'F7826DA6-ASDF-ASDF-8024-BC5B71E0893E'
);
this.ibeacon.startMonitoringForRegion(beaconRegion).then(
() => console.log('Native layer received the request to monitoring'),
(error) =>
console.error('Native layer failed to begin monitoring: ', error)
);
}
}
Also I imported the IBeacon module inside my module.ts like so :
import { NgModule } from '#angular/core';
import { CommonModule } from '#angular/common';
import { FormsModule } from '#angular/forms';
import { IonicModule } from '#ionic/angular';
import { BeaconPageRoutingModule } from './beacon-routing.module';
import { BeaconPage } from './beacon.page';
import { IBeacon } from '#ionic-native/ibeacon/ngx';
#NgModule({
imports: [CommonModule, FormsModule, IonicModule, BeaconPageRoutingModule],
declarations: [BeaconPage],
providers: [IBeacon],
})
export class BeaconPageModule {}
Did I forget to do something ? Why is device undefined ? Should I also import the device library ?
I should mention I have the device library installed.
Inside the lib they use the device to check the plataform, that is the code:
BeaconRegion.isValidUuid = function (uuid) {
// https://github.com/petermetz/cordova-plugin-ibeacon/issues/328
// If we are on Android, then allow the UUID to be specified as a wild-card (omitted)
var isAndroid = device && device.platform === "Android";
if (uuid === BeaconRegion.WILDCARD_UUID && isAndroid) {
return true;
}
var uuidValidatorRegex = this.getUuidValidatorRegex();
return uuid.match(uuidValidatorRegex) != null;
};
You can check right here https://github.com/petermetz/cordova-plugin-ibeacon/blob/270ffbbc12159861a16e5e81481103c1e09139cb/www/model/BeaconRegion.js#L38
So, you have to install the following plugin-in https://ionicframework.com/docs/native/device
npm install cordova-plugin-device
npm install #ionic-native/device
ionic cap sync
Then the find this device reference and the problem will be solved.

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.

How to fix (unreachable code ts.7027) react native

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

undefined is not an object (evaluating '_reactNativeContacts.default.getAll')

I am trying du use react-native-contacts with a react-native app made with Expo, but I have this error message :
undefined is not an object (evaluating '_reactNativeContacts.default.getAll')
Here is the code I use :
import React from 'react';
import {
Image,
Platform,
ScrollView,
StyleSheet,
Text,
TouchableOpacity,
View,
Modal,
TouchableHighlight,
ImageBackground,
TextInput,
Picker,
PermissionsAndroid
} from 'react-native';
import { WebBrowser } from 'expo';
import Contacts from 'react-native-contacts';
import { MonoText } from '../components/StyledText';
Contacts.getAll((err, contacts) => {
if (err === 'denied'){
// error
} else {
// contacts returned in Array
}
})
I tried to follow all he steps for the installation in this page for the android part :
https://github.com/rt2zz/react-native-contacts#getting-started
But I don't find where I can do this part :
I don't know where I can find this file : android/settings.gradle
By the way I tried this command "react-native link" in my app directory and nothing changed.
Android
In android/settings.gradle
...
include ':react-native-contacts'
project(':react-native-contacts').projectDir = new File(rootProject.projectDir, '../node_modules/react-native-contacts/android')
In android/app/build.gradle
...
dependencies {
...
implementation project(':react-native-contacts')
}
Has anyone had this kind of problem ?
Thanks for help !
As far as I understand, you are developing your app with Expo. Some of independent libraries doesn't work well with Expo. I have two suggestions for you.
If you want to keep using react-native-contacts, you need to eject your app from Expo
Or directly use Expo's contacts api, You can find the details in this link Expo's Contacts I would do this which is less work for you to do and solve your problem
import { Contacts } from 'expo';
const { data } = await Contacts.getContactsAsync({
fields: [Contacts.Fields.Emails],
});
if (data.length > 0) {
const contact = data[0];
console.log(contact);
}
You can find same issue created in react-native-contacts github page . Issue
July 2021 update
The Contacts module has been moved from the core expo package to expo-contacts (see documentation).
Example:
import * as Contacts from 'expo-contacts';
const { status } = await Contacts.requestPermissionsAsync();
if (status === 'granted') {
const { data: contacts } = await Contacts.getContactsAsync();
console.log('Retrieved contacts!', contacts);
}

Categories

Resources