i try to make simple CRUD app froem react native with fire base but i keep getting this error when connecting firebase with app in register view
the function is to register a new user to database in firebase
The error
My register view.js
import React, {Component} from 'react';
import {Text,TextInput, View, Image } from 'react-native';
import Waiter_login from '../../../components/molecules/Waiter_login/';
import firebase from 'firebase';
import 'firebase/firestore';
class Register extends Component{
constructor() {
super();
this.dbRef = firebase.firestore().collection('users');
this.state = {
email: '',
username: '',
password: '',
isLoading: false
};
}
inputValueUpdate = (val, prop) => {
const state = this.state;
state[prop] = val;
this.setState(state);
}
storeUser() {
if(this.state.username === ''){
alert('Isi username kamu!')
} else {
this.setState({
isLoading: true,
});
this.dbRef.add({
email: this.state.email,
username: this.state.username,
password: this.state.password,
}).then((res) => {
this.setState({
email: '',
username: '',
password: '',
isLoading: false,
});
this.props.navigation.navigate('Login')
})
.catch((err) => {
console.error("Error found: ", err);
this.setState({
isLoading: false,
});
});
}
}
render(){
const { navigate } = this.props.navigation;
return (
<View style={{flex:1}}>
<View style={{flex:1,backgroundColor:'white'}}>
<Waiter_login title='Please Register Here' img={require('../../../assets/register-fam.png')} />
<View style={{ marginLeft:50,marginRight:50,textAlign: 'center', marginVertical: 5}}>
<TextInput placeholder="Username" style={{ marginTop:10, height: 40, width: 300,paddingLeft:15, borderColor: 'gray', borderWidth: 1, borderRadius:25}} value={this.state.username} /*onChangeText={text => onChangeText(text)}*/onChangeText={(val) => this.inputValueUpdate(val, 'username')} />
<TextInput placeholder="Password" style={{ marginTop:10, height: 40, width: 300,paddingLeft:15, borderColor: 'gray', borderWidth: 1, borderRadius:25}} onChangeText={text => onChangeText(text)}/>
<TextInput placeholder="Phone" style={{ marginTop:10, height: 40, width: 300,paddingLeft:15, borderColor: 'gray', borderWidth: 1, borderRadius:25}} onChangeText={text => onChangeText(text)}/>
<TextInput placeholder="Email" style={{ marginTop:10, height: 40, width: 300,paddingLeft:15, borderColor: 'gray', borderWidth: 1, borderRadius:25}} onChangeText={text => onChangeText(text)}/>
<View style={{backgroundColor:'#432f96', borderRadius:15,marginTop:20,paddingBottom:7,paddingTop:7}}>
<Text style={{fontSize:22,fontWeight: 'bold', color:'white',textAlign:'center'}} onPress=/*{() => navigate('Login')}*/{() => this.storeUser()} >Register</Text>
</View>
</View>
{/* <View style={{backgroundColor:'#ffff',marginTop:20,marginLeft:50,marginRight:50}}>
<Image style={{height:67,width:310}} source={require('./src/assets/login_google.png')} />
</View> */}
</View>
<View style={{height:40,backgroundColor:'#ededed'}}>
<View style={{alignSelf:'center',marginTop:5}}>
<Text style={{fontSize:12, color:'grey'}}>made with love BudakBandung</Text>
</View>
</View>
</View>
)
}
}
export default Register;
My firebase.js
import * as firebase from 'firebase';
import 'firebase/firestore';
const firebaseConfig={
apiKey: "AIzaSyCHTSbVaLFiIvb7QOfzQEdcPxCPCt_5gA4",
authDomain: "pesendulu-9dd4f.firebaseapp.com",
databaseURL: "https://pesendulu-9dd4f.firebaseio.com",
projectId: "pesendulu-9dd4f",
storageBucket: "pesendulu-9dd4f.appspot.com",
messagingSenderId: "733125666943",
appId: "1:733125666943:web:5980721527735d9235b74a",
measurementId: "G-3TE04D9S77"
};
if (!firebase.apps.length) {
firebase.initializeApp(config);
};
firebase.firestore().settings(settings);
export default firebase;
what is the problem and what should i do to make it work ? thanks before
if (!firebase.apps.length) { firebase.initializeApp(firebaseConfig);}
use this code,this code will fix your issue
Related
I have set up a Firebase Auth in my react native app. I managed to run the app and create new user using email and password.
I did try to add create new user by defining new var to add new user's name table, then store the new name table in firebase using by defining db = firebase.firestore();, then inject new user's name using db.collection("users"), but it's not working. I got this error "Warning: Can't perform a React state update on an unmounted component. This is a no-op, but it indicates a memory leak in your application. To fix, cancel all subscriptions and asynchronous tasks in a useEffect cleanup function."
How can I add new table in Firebase Auth on my react native expo app?
Here is my signup.js and firebase.js files.
import { StatusBar } from 'expo-status-bar';
import React from 'react';
import { useState } from 'react';
import { StyleSheet, Text, View, Button as RNButton } from 'react-native';
import { Button, InputField, ErrorMessage } from '../components';
import Firebase from '../config/firebase';
const auth = Firebase.auth();
export default function SignupScreen({ navigation }) {
const [displayName, setDisplayName] = useState('');
const [email, setEmail] = useState('');
const [password, setPassword] = useState('');
const [passwordVisibility, setPasswordVisibility] = useState(true);
const [rightIcon, setRightIcon] = useState('eye');
const [signupError, setSignupError] = useState('');
const handlePasswordVisibility = () => {
if (rightIcon === 'eye') {
setRightIcon('eye-off');
setPasswordVisibility(!passwordVisibility);
} else if (rightIcon === 'eye-off') {
setRightIcon('eye');
setPasswordVisibility(!passwordVisibility);
}
};
const onHandleSignup = async () => {
try {
if (email !== '' && password !== '') {
await auth.createUserWithEmailAndPassword(email, password);
const currentUser = firebase.auth().currentUser;
const db = firebase.firestore();
db.collection("users")
.doc(currentUser.uid)
.set({
email: currentUser.email,
displayName: displayName,
});
}
} catch (error) {
setSignupError(error.message);
}
};
return (
<View style={styles.container}>
<StatusBar style='dark-content' />
<Text style={styles.title}>Create new account</Text>
<InputField
inputStyle={{
fontSize: 14
}}
containerStyle={{
backgroundColor: '#fff',
marginBottom: 20
}}
leftIcon='account'
placeholder='Nick name'
autoCapitalize='none'
textContentType='name'
autoFocus={true}
value={displayName}
onChangeText={text => setDisplayName(text)}
/>
<InputField
inputStyle={{
fontSize: 14
}}
containerStyle={{
backgroundColor: '#fff',
marginBottom: 20
}}
leftIcon='email'
placeholder='Enter email'
autoCapitalize='none'
keyboardType='email-address'
textContentType='emailAddress'
autoFocus={true}
value={email}
onChangeText={text => setEmail(text)}
/>
<InputField
inputStyle={{
fontSize: 14
}}
containerStyle={{
backgroundColor: '#fff',
marginBottom: 20
}}
leftIcon='lock'
placeholder='Enter password'
autoCapitalize='none'
autoCorrect={false}
secureTextEntry={passwordVisibility}
textContentType='password'
rightIcon={rightIcon}
value={password}
onChangeText={text => setPassword(text)}
handlePasswordVisibility={handlePasswordVisibility}
/>
{signupError ? <ErrorMessage error={signupError} visible={true} /> : null}
<Button
onPress={onHandleSignup}
backgroundColor='#f57c00'
title='Signup'
tileColor='#fff'
titleSize={20}
containerStyle={{
marginBottom: 24
}}
/>
<RNButton
onPress={() => navigation.navigate('Login')}
title='Go to Login'
color='#fff'
/>
</View>
);
}
const styles = StyleSheet.create({
container: {
flex: 1,
backgroundColor: '#e93b81',
paddingTop: 50,
paddingHorizontal: 12
},
title: {
fontSize: 24,
fontWeight: '600',
color: '#fff',
alignSelf: 'center',
paddingBottom: 24
}
});
import 'firebase/compat/auth';
import 'firebase/compat/firestore';
import Constants from 'expo-constants';
// Initialize Firebase
const firebaseConfig = {
apiKey: Constants.manifest.extra.apiKey,
authDomain: Constants.manifest.extra.authDomain,
projectId: Constants.manifest.extra.projectId,
storageBucket: Constants.manifest.extra.storageBucket,
messagingSenderId: Constants.manifest.extra.messagingSenderId,
appId: Constants.manifest.extra.appId
};
let Firebase;
if (firebase.apps.length === 0) {
Firebase = firebase.initializeApp(firebaseConfig);
}
export default Firebase;
You could try moving this to cloud functions, creating a listener to user creation events.
export const onCreateUser = functions.auth.user().onCreate(async (user) => {
const customerData = {
// ...more data here
email: user.email,
id: user.id
}
})
You can find more useful documentation here: https://firebase.google.com/docs/functions/auth-events
Expo recently launched the expo-firebase-recaptcha library and i am trying to implement it in my app. The recaptcha occurs succesfully to test if i am a robot however i am not getting the text message with the verification code. What am i doing wrong? Any help would be appreciated.
Heres a snippet of my code
import * as firebase from "firebase/app";
import "firebase/auth";
import {
FirebaseRecaptchaVerifierModal,
FirebaseAuthApplicationVerifier
} from "expo-firebase-recaptcha";
var config = {
apiKey: "",
authDomain: "",
databaseURL: "",
projectId: "",
storageBucket: "",
messagingSenderId: "",
appId: ""
};
if (!firebase.apps.length) {
firebase.initializeApp(config);
}
function LoginScreen() {
const recaptchaVerifier = React.createRef();
async onSendOtp(){
if(this.state.phone!="")
{
try{
this.setState({Otp:!this.state.Otp})
var phoneNumber = this.state.phone;
console.log("Phone"+phoneNumber);
const phoneProvider = new firebase.auth.PhoneAuthProvider();
const verificationid = await phoneProvider.verifyPhoneNumber(
phoneNumber,
recaptchaVerifier.current
);
this.setState({
verificationId:verificationid
})
console.log("Message sent"+this.state.verificationId);
}catch(err){
console.log("Error message"+err)
}
}
else
{
Alert.alert("Enter phone number");
}
}
return (
<View style={{ width: "100%", flex: 1, paddingHorizontal: 30 }}>
<Title>Login</Title>
<FirebaseRecaptchaVerifierModal
ref={recaptchaVerifier}
firebaseConfig={config}
/>
<View style={styles.inputContainer}>
<Icon style={styles.inputIcon} name="mobile-phone"/>
<TextInput style={styles.inputs}
placeholder="Phone number"
autoCapitalize="none"
keyboardType="numeric"
underlineColorAndroid='transparent'
maxLength={10}
onChangeText={(text)=>this.phonenumberchange(text)}/>
</View>
<TouchableHighlight style={[styles.buttonContainer, styles.signupButton]} onPress={() => this.onSendOtp()}>
<Text id="sendcode" style={styles.signUpText}>SEND CONFIRMATION CODE</Text>
</TouchableHighlight>
</View> );
}
const Phoneauthentication=({navigation})=>{
const recaptchaVerifier = useRef(null);
const [phoneNumber, setPhoneNumber] =useState();
const [verificationId, setVerificationId] =useState();
const [verificationCode, setVerificationCode] =useState();
const firebaseConfig = firebaseconfig;
const [message, showMessage] = useState((!firebaseConfig || Platform.OS === 'web')
? { text: "To get started, provide a valid firebase config in App.js and open this snack on an iOS or Android device."}
: undefined);
return (
<View style={{ padding: 20, marginTop: 50 }}>
<FirebaseRecaptchaVerifierModal
ref={recaptchaVerifier}
firebaseConfig={firebaseConfig}
style={{ margin:0, left: 0, top:-10, right: 0, bottom: 0 }}
title="Hello"
/>
<Text style={{ marginTop: 20 }}>Enter phone number</Text>
<TextInput
style={{ marginVertical: 10, fontSize: 17 }}
placeholder="+92 331 969 9999"
autoFocus
autoCompleteType="tel"
keyboardType="phone-pad"
textContentType="telephoneNumber"
onChangeText={(phoneNumber) => setPhoneNumber(phoneNumber)}
/>
<Button
title="Send Verification Code"
disabled={!phoneNumber}
onPress={async () => {
// The FirebaseRecaptchaVerifierModal ref implements the
// FirebaseAuthApplicationVerifier interface and can be
// passed directly to `verifyPhoneNumber`.
try {
const phoneProvider = new firebase.auth.PhoneAuthProvider();
const verificationId = await phoneProvider.verifyPhoneNumber(
phoneNumber,
recaptchaVerifier.current
);
setVerificationId(verificationId);
showMessage({
text:"Verification code has been sent to your phone.",
});
} catch (err) {
showMessage({ text:`Error: ${err.message}`,color: "red" });
}
}}
/>
<Text style={{ marginTop: 20 }}>Enter Verification code</Text>
<TextInput
style={{ marginVertical: 10,fontSize: 17 }}
editable={!!verificationId}
placeholder="123456"
onChangeText={setVerificationCode}
/>
<Button
title="Confirm Verification Code"
disabled={!verificationId}
onPress={async () => {
try {
const credential = firebase.auth.PhoneAuthProvider.credential(
verificationId,
verificationCode
);
await firebase.auth().signInWithCredential(credential);
showMessage({text:'Phone authentication successful 👍'||navigation.goback()});
} catch (err) {
showMessage({ text: `Error: ${err.message}`, color: "red",marginTop:220 });
}
}}
/>
{message ? (
<TouchableOpacity
style={[StyleSheet.absoluteFill, { backgroundColor: 0xffffffee, justifyContent: "center" }]}
onPress={() => showMessage(undefined)}>
<Text style={{color: message.color || "blue", fontSize: 17, textAlign: "center", margin:20, }}>
{message.text}
</Text>
</TouchableOpacity>
) : undefined}
</View>
);
}
export default PhoneAuth;
i installed firebase to my project folder and i can see it in node modules folder, but still when i try import firebase from 'firebase' nothing happens
i don't know why i uninstalled it and re installed it
i searched for this problem but with no solution to found it like firebase module does not exist at all
i even restarted my computer
i cannot even intializeApp
i have tried to change my import line too
import React from 'react'
import {
View,
Button,
TextInput,
StyleSheet,
Image,
} from 'react-native'
// import firebase from 'firebase';
import * as firebase from 'firebase'
const firebaseConfig={
apiKey: "AIzaSyCDh998mIGLdyHaE3EK5tRnhLY-I7jiPOY",
authDomain: "shiftorgnaizer.firebaseapp.com",
databaseURL: "https://shiftorgnaizer.firebaseio.com",
projectId: "shiftorgnaizer",
storageBucket: ""
};
export default class SignUp extends React.Component {
state = {
username: '', password: '', email: '', phone_number: ''
}
onChangeText = (key, val) => {
this.setState({ [key]: val })
}
signUp = async () => {
const { username, password, email, phone_number } = this.state
}
render() {
return (
<View style={styles.container}>
<Image source={require('./Images/allImages.jpg')}
style={{width: 150,height: 100}}/>
<TextInput
style={styles.input}
placeholder='Username'
autoCapitalize="none"
placeholderTextColor='white'
onChangeText={val => this.onChangeText('username', val)}
/>
<TextInput
style={styles.input}
placeholder='Password'
secureTextEntry={true}
autoCapitalize="none"
placeholderTextColor='white'
onChangeText={val => this.onChangeText('password', val)}
/>
<TextInput
style={styles.input}
placeholder='Email'
autoCapitalize="none"
placeholderTextColor='white'
onChangeText={val => this.onChangeText('email', val)}
/>
<TextInput
style={styles.input}
placeholder='Phone Number'
autoCapitalize="none"
placeholderTextColor='white'
onChangeText={val => this.onChangeText('phone_number', val)}
/>
<Button
title='Sign Up'
onPress={this.signUp}
/>
</View>
)
}
}
const styles = StyleSheet.create({
input: {
width: 350,
height: 55,
backgroundColor: '#42A5F5',
margin: 10,
padding: 8,
color: 'white',
borderRadius: 14,
fontSize: 18,
fontWeight: '500',
},
container: {
flex: 1,
justifyContent: 'center',
alignItems: 'center'
}
})
expected to recognize the module and work with firebase
I'm trying when I press Login button to go to Drawer screen which contains all my other screens but I'm getting the following error:
TypeError: undefined is not an object (evaluating
'this.props.navigation.navigate')
Here is my DrawerScreen:
import React, {Component} from 'react';
import { Button, View, Text, Dimensions, ImageBackground } from 'react-native';
import { createStackNavigator, createAppContainer, createDrawerNavigator, DrawerItems } from 'react-navigation';
import HomeScreen from './HomeScreen';
import AboutScreen from './AboutScreen';
import Count from './CountScreen';
const DrawerContent = (props) => (
<View>
<ImageBackground
source={{uri:'https://cdn.pixabay.com/photo/2017/12/13/07/15/natural-3016177_960_720.jpg'}}
style={{}}
imageStyle= {{opacity: 0.7}}
>
<View
style={{
//backgroundColor: '#73a2ef',
height: 140,
alignItems: 'center',
justifyContent: 'center',
}}
>
<Text style={{ color: 'black', fontSize: 40, fontWeight: 'bold' }}>
Menu
</Text>
</View>
</ImageBackground>
<DrawerItems {...props} />
</View>
)
const WIDTF = Dimensions.get('window').width;
const DrawerConfig = {
drawerWidth: WIDTF*0.80,
drawertType: 'back',
}
const Drawer = createDrawerNavigator ({
Home: {
screen: HomeScreen
},
About: {
screen: AboutScreen
},
Count: {
screen: Count
},
},
{
drawerBackgroundColor: '#c7d1a7',
contentComponent: DrawerContent,
contentOptions: {
activeTintColor: 'blue',
style: {
flex: 1,
paddingTop: 15,
}
}},
DrawerConfig
);
const AppContainer = createAppContainer(Drawer);
export default AppContainer;
And here is my LogInScreen:
import React, {Component} from 'react';
import * as firebase from 'firebase';
import {Container, Content, Header, Form, Input, Item, Button, Label, Drawer} from 'native-base';
import {StyleSheet, Text} from 'react-native';
import AppContainer from './DrawerNavigatorNew';
const firebaseConfig = {
apiKey:
authDomain:
databaseURL:
projectId:
storageBucket:
};
firebase.initializeApp(firebaseConfig);
export default class LoginScreen extends React.Component {
constructor (props) {
super(props)
this.state =({
email:'',
password:'',
})
}
signUpUser = (email, password) => {
try {
if(this.state.password.length <6)
{
alert("Please enter atleast 6 characters")
return;
}
firebase.auth().createUserWithEmailAndPassword(email, password)
}
catch (error){
console.log(error.toString())
}
}
loginUser =(email, password) => {
try{
firebase.auth().signInWithEmailAndPassword(email, password).then(function(user){
console.log(user)
})
}
catch (error) {
console.log(error.toString())
}
}
render() {
const {navigate} = this.props.navigation;
return (
<Container style={styles.container}>
<Form>
<Item floatingLabel>
<Label> Email </Label>
<Input
name='email'
autoCorrect={false}
autoCapitalize='none'
onChangeText={(email)=> this.setState({email})}
/>
</Item>
<Item floatingLabel>
<Label> Password </Label>
<Input
name='password'
secureTextEntry={true}
autoCorrect={false}
autoCapitalize='none'
onChangeText={(password)=> this.setState({password})}
/>
</Item>
<Button style={{marginTop: 10}}
full
rounded
success
onPress = {()=> this.loginUser(this.state.email,this.state.password) || navigate(AppContainer)}
>
<Text> Login </Text>
</Button>
<Button style={{marginTop: 10}}
full
rounded
primary
onPress = {()=> this.signUpUser(this.state.email,this.state.password)}
>
<Text style={{color: 'white' }}> Sign Up </Text>
</Button>
</Form>
</Container>
);
}
}
const styles = StyleSheet.create ({
container:{
flex: 1,
backgroundColor: 'white',
justifyContent: 'center',
padding: 10
}
})
And the Error:
I misread the code. 'Navigate' is a command to move the screen. The 'createDrawenavigator' must open the drawer.
Can you try this Code?
onPress = {()=> this.loginUser(this.state.email,this.state.password) || this.props.navigation.openDrawer();}
Change the Navigator configuration if you want to move the screen.
createStackNavigator({
A: {
screen: AScreen,
navigationOptions: () => ({
title: `A`,
headerBackTitle: 'A much too long text for back button from B to A',
headerTruncatedBackTitle: `to A`
}),
},
B: {
screen: BScreen,
navigationOptions: () => ({
title: `B`,
}),
}
});
I am working with Firebase authentification in my React Native android app, however every time I try to login and press the button, it gives me this error:
Object is not a function(evaluating 'this2.state'({
error: 'Authentification failed', loading: false
}))
I have looked up similar answers as well, but it doesn't seem to match my problem. Any help would be appreciated.
Here is my code:
import React from 'react';
import {
AppRegistry,
StyleSheet,
Text,
View,
PixelRatio,
TouchableOpacity,
Image,
Button,
} from 'react-native';
import * as firebase from 'firebase';
import { FormLabel, FormInput } from 'react-native-elements';
import Help from './app/components/Help';
import { Input } from './app/components/Input';
const util = require('util');
firebase.initializeApp({
apiKey: 'AIzaSyCmjeFuDoMeOkeG5J-TCXzDJ1vtaDqUXjE',
authDomain: 'dev-pre-do.firebaseapp.com',
databaseURL: 'https://dev-pre-do.firebaseio.com',
projectId: 'dev-pre-do',
storageBucket: 'dev-pre-do.appspot.com',
messagingSenderId: '943752089124'
}
);
class LoginScreen extends React.Component {
static navigationOptions ={
header: null,
};
constructor(props) {
super(props);
this.state = {email:'', password:'', error: '', loading:false};
}
onLoginPress(){
this.setState({error:'', loading:true});
const{email, password} = this.state;
firebase.auth().signInWithEmailAndPassword(email, password)
.then(() => {
this.state({error: '', loading: false});
this.props.navigation.navigate('CreateIdeaMenu');
})
.catch(() => {
this.state({error: 'Authentification failed', loading: false});
})
}
renderButtonOrLoading(){
if(this.state.loading) {
return (
<Text style={styles.loading}> Loading </Text>
)}
return (
<View>
<Button style={styles.Button} title='Login'
onPress={this.onLoginPress.bind(this)}></Button>
</View>
)
}
render() {
return (
<View style={styles.container}>
<Help onPress = {()=> navigate("HelpFirst")}/>
<Image style={styles.logo}
source={require('./app/images/PREDO_logo_white.png')}
/>
<FormLabel> Email</FormLabel>
<FormInput onChangeText={email => this.setState({ email })}/>
<FormLabel> Password</FormLabel>
<FormInput onChangeText={password => this.setState({ password })}/>
<Text>{this.state.error}</Text>
{/* <Input
placeholder='Email'
label='Email'
onChangeText={email => this.setState({ email })}
value={this.state.email}
/>
<Input
placeholder='Password'
label='Password'
secureTextEntry
onChangeText={password => this.setState({ password })}
value={this.state.password} */}
{this.renderButtonOrLoading()}
{/* <Button onPress={() => console.log('pressed')}>Log in</Button>*/}
{/* <RegForm onPress = {()=> navigate("CreateIdeaMenu")} /> */}
</View>
);
}
};
const styles = StyleSheet.create({
container: {
flex:1,
justifyContent: 'flex-start',
alignItems: 'center',
backgroundColor: '#1e1f20',
paddingLeft: 60,
paddingRight: 60,
paddingTop: 10,
},
Button: {
width: 200,
height:100,
marginBottom: 10,
backgroundColor: 'purple',
alignItems: 'center',
justifyContent: 'center',
},
logo: {
width: 360,
height:94,
marginBottom: 80,
marginTop: 20,
},
loading: {
color: 'white',
fontSize: 50,
}
});
export default LoginScreen;
Update your code as below:
onLoginPress(){
this.setState({error:'', loading:true});
const{email, password} = this.state;
firebase.auth().signInWithEmailAndPassword(email, password)
.then(() => {
this.setState({error: '', loading: false});
this.props.navigation.navigate('CreateIdeaMenu');
})
.catch(() => {
this.setState({error: 'Authentification failed', loading: false});
})
}