React-Native Passing users email and password to submit button - firebase

import FirebaseAPI from '../MyModules/FirebaseAPI';
function submit() {
import FirebaseAPI from '../MyModules/FirebaseAPI';
export default function LinksScreen() {
const [email, onChangeText] = React.useState('Enter Email');
const [password, onChangeText2] = React.useState('Enter Password');
const submit = () => {
FirebaseAPI.createUser(email, password)
}
return (
<KeyboardAvoidingView style={styles.wrapper} behavior="padding">
<View style={styles.scrollViewWrapper}>
<ScrollView style={styles.scrollView}>
<Text style={styles.loginHeader}>Creat an Account </Text>
<TextInput
style={{ height: 40, borderColor: 'gray', borderWidth: 1 }}
onChangeText={text => onChangeText(text)}
value={email}
/>
<TextInput
style={{ height: 40, borderColor: 'gray', borderWidth: 1 }}
onChangeText={text => onChangeText2(text)}
value={password}
/>
<TouchableOpacity
style={{marginTop: '5%'}}
onPress= {submit()}>
<View>
<Text>Submit</Text>
</View>
//code from FirebaseAPI.js
import * as firebase from 'firebase'
export const createUser = (email, password) => {
firebase.auth().createUserWithEmailAndPassword(email, password)
.catch((error) => console.log('createUser error: ', error));
}
//etc
my error is
TypeError: undefined is not an object (evaluating '_FirebaseAPI.default.createUser')
I assume its a scoping issue but unsure on how to fix it. Still new at react. Any help would be awesome!

The email and password are not scope of the submit function. You either need to move the submit function inside the component function or pass the values to the function
export default function LinksScreen() {
const [email, onChangeText] = React.useState('Enter Email');
const [password, onChangeText2] = React.useState('Enter Password');
const submit = () => {
FirebaseAPI.createUser(email, password)
}
return (
....
)
OR
<TouchableOpacity
style={{marginTop: '5%'}}
onPress= {() => submit(email, password)}>
<View>
<Text>Submit</Text>
</View>
</TouchableOpacity>
Also where you are importing the FirebaseAPI import as
import * as FirebaseAPI from '../MyModules/FirebaseAPI';

Related

Error: [auth/unknown] Cannot create PhoneAuthCredential without either verificationProof, sessionInfo, temporary proof, or enrollment ID

I am trying to make a Login page with Phone Authentication to use React-Native-Firebase sdk and I receive OTP through sms and when I confirm the received OTP ,I got a error that: [Error: [auth/unknown] Cannot create PhoneAuthCredential without either verificationProof, sessionInfo, temporary proof, or enrollment ID.]
I am using-
React:18.0.0
React-Native: 0.69.1
React-Native-Firebase:^15.1.1
My code is-
import React, {useState} from 'react';
import {
View,
Text,
StyleSheet,
Image,
TextInput,
TouchableOpacity,
Alert,
} from 'react-native';
import PhoneInput from 'react-native-phone-number-input';
import auth from '#react-native-firebase/auth';
const Login = () => {
const [PhoneNumber, setPhoneNumber] = useState('');
const [otpInput, setOtpInput] = useState('');
const [confirmData, setConfirmData] = useState('');
const sendOtp = async () => {
try {
const responce = await auth().signInWithPhoneNumber(PhoneNumber);
setConfirmData(responce);
console.log(responce);
Alert.alert('Otp is sent please varify it');
} catch (error) {
console.log(error);
}
}
const submitOtp = async () => {
try {
const responce = await confirmData.confirm(otpInput);
console.log(responce);
Alert.alert('Your Number is verified');
} catch (error) {
console.log(error);
}
}
return (
<View>
<View style={styles.con}>
<Text style={styles.container}>Login Screen</Text>
<Image source={require('../assets/logo.png')} style={styles.image} />
</View>
<View style={styles.inputContainer}>
<Text style={styles.labels}>Phone Number:</Text>
<PhoneInput
style={styles.inputStyle}
defaultValue={PhoneNumber}
defaultCode="DM"
layout="first"
keyboardType="number-pad"
onChangeFormattedText={text => setPhoneNumber(text)}
onChangeText={(value) => setPhoneNumber(value)}
/>
</View>
<View>
<TouchableOpacity
style={styles.buttonStyle}>
<Text style={styles.buttonText}>Verify</Text>
</TouchableOpacity>
</View>
<View style={styles.otpContainer}>
<TextInput
style={styles.otpStyle}
placeholder="Enter OTP"
autoCapitalize="none"
secureTextEntry={true}
onChangeText={(value) => setOtpInput(value)}/>
</View>
<View>
<TouchableOpacity style={styles.continueStyle}>
<Text
style={styles.buttonText}
onPress={() => submitOtp()}>
Continue
</Text>
</TouchableOpacity>
</View>
</View>
);
};
export default Login;

Adding doc to firebase using react native and encountering many errors with promises/async storage

So im trying to make a todo list app and making the fucntion to add a doc to firebase. However, when i do that expo says the async storage has been deprecated and that there is a unhandled promise rejection
my code in my app:
import React, { useEffect } from 'react';
import {useState} from "react"
import { SafeAreaView, Text, View, Button, TouchableOpacity, Modal, StyleSheet,Pressable, TextInput } from 'react-native';
import { collection, doc, setDoc, query, getDocs, onSnapshot, addDoc, orderBy, limit, Timestamp, where} from "firebase/firestore";
import {db} from "../firebase"
import { signPlsOut } from '../firebase';
import { auth } from '../firebase';
import AsyncStorage from '#react-native-async-storage/async-storage';
export const Dashboard = () => {
const {uid, photoURL, displayName} = auth.currentUser;
const projectsref = collection(db, "projects");
const [modalVisible, setModalVisible] = useState(false);
const [projects, setProjects] = useState([])
const [desc, setDesc] = useState("");
const [title, setTitle] = useState("");
async function handleAddTask () {
try {
await addDoc(projectsref, {
title: title,
desc: desc,
createdAt: Timestamp.fromDate(new Date()),
uid: uid,
})
setTitle("")
setDesc("")
setModalVisible(false)
}
catch(error) {
console.log('There has been a problem with your fetch operation: ' + error.message);
// ADD THIS THROW error
throw error;
}
}
return (
<SafeAreaView>
<View style={{
margin: 20
}}>
<Modal
animationType="slide"
transparent={true}
visible={modalVisible}
onRequestClose={() => {
Alert.alert("Modal has been closed.");
setModalVisible(!modalVisible);
}}
>
<View style={styles.centeredView}>
<View style={styles.modalView}>
<Text style={styles.modalText}>Add task:</Text>
<View style={{marginBottom: 20}}>
<TextInput placeholder='title' value={title} onChange={(e) => setTitle(e.target.value)}></TextInput>
<TextInput placeholder='description' value={desc} onChange={(e) => setDesc(e.target.value)}></TextInput>
</View>
<Button title='submit todo' onPress={handleAddTask}></Button>
<Pressable
style={[styles.button, styles.buttonClose]}
onPress={() => setModalVisible(!modalVisible)}
>
<Text style={styles.textStyle}>Cancel</Text>
</Pressable>
</View>
</View>
</Modal>
<Text style={{fontSize: 20, fontWeight: "500"}}>Welcome,</Text>
<Text style={{fontSize: 27, fontWeight: "700"}}>{auth.currentUser.email}</Text>
<View style={{marginTop: 30}}>
<Text style={{fontSize: 40, fontWeight: "700", color: "#0404"}}>Create Task</Text>
<TouchableOpacity>
<View style={{
backgroundColor: "orange",
borderRadius: "20px"
}}>
<Pressable
style={[styles.button, styles.buttonOpen]}
onPress={() => setModalVisible(true)}
>
<Text style={styles.textStyle}>Add task</Text>
</Pressable>
</View>
</TouchableOpacity>
</View>
<Button title="signout" onPress={signPlsOut}></Button>
</View>
</SafeAreaView>
);
};
error:
async sotrage has been extracted and will be removed in a future release, in addition to the unhandled promise rejection error
Are you able to actually add the doc to firebase? Some more context would be helpful in what you're trying to do. Is you code above completely unsucessful and you are getting errors? Or are you simply trying to clear errors.
If you are just trying to get rid of the unhandled promise rejection. I ran into a similar error and I found where in the Firebase app node_module where the call out was being for async storage. For me to get rid of a similar error i did two steps:
First, i installed the new react native async storage module:
npm install #react-native-async-storage/async-storage
Next, i had to update firebase app module, in the following file, to point to the appropriate API within my expo app to point to this new react native async storage module.
./node_modules/#firebase/app/dist/index.rn.cjs.js
I had to adjust this bit of code in this file:
var AsyncStorage = require('#react-native-async-storage/async-storage').AsyncStorage;
firebase.INTERNAL.extendNamespace({
INTERNAL: {
reactNative: {
AsyncStorage: AsyncStorage
}
}
});
The above code previously called to "react" i believe, i just needed to update it to specifically call to "#react-native-async-storage/async-storage". And this solved my problem.

Firebase react native flatlist keyExtractor

Im displaying some firebase data in a flatlist and im having trouble with the keyExtractor, I keep having the error:
undefined is not an object (evaluating "item.id")
I have added an id field to all my data in firebase and made sure they were a string but it's still not recognizing it as an id.
function Squad() {
const [gk, setGk] = useState([]);
useEffect(() => {
db.collection('squad').orderBy('position').get().then(snapshot => {
const gkData = snapshot.map(doc => {
const playerObject = doc.data();
return { name: playerObject.name, number: playerObject.number, id: playerObject.id };
});
setGk(gkData);
console.log(setGk);
});
}, []);
const Item = ({ name, number }) => (
<View style={styles.item}>
<Text style={styles.itemText}>{number} - {name}</Text>
</View>
);
const renderItem = ({ item }) => (
<Item name={item.name} number={item.number} />
)
return(
<View>
<View style={globalStyles.bar}>
<Text style={globalStyles.barText}>goalkeeper</Text>
</View>
<FlatList
data={setGk}
renderItem={renderItem}
keyExtractor={item => item.id}
/>
</View>
)
}
The data you are passing into the Flatlist is the setter function! You want to pass in ‘gk’ not ‘setGk’

How to use firebase in DrawerNavigator and sync retrieve data

Objective:
I want to retrieve the users name from firebase and then use in the Text component, but it returns before the data can be loaded from firebase, which causes the Text gets undefined.
The Drawer code:
export default Slidebar = (props) => {
var name;
firebase.database().ref('users/' + firebase.auth().currentUser.uid + '/profile').once("value")
.then( (snapshot) => {
name = (snapshot.val().name)
console.log('snapshot name:', name)
})
return(
<ScrollView style={{backgroundColor: "#121212"}}>
<ImageBackground source={{uri: 'https://www.redebrasilatual.com.br/wp-content/uploads/2019/05/maconha-projeto.jpg'}}
style={{ padding: 16, paddingTop: 48 }}
>
<Text style={styles.name}> { name, console.log('text name: ', name) } </Text>
<Text style={styles.email}>email#example.com</Text>
<TouchableOpacity style={{height: 40, width: 40}} onPress={() => console.log(name)} >
<View style={{flex: 1, backgroundColor: 'white'}} />
</TouchableOpacity>
</ImageBackground>
<View style={styles.container}>
<DrawerNavigatorItems {...props} />
</View>
</ScrollView>
)
}
The console output:
INFO
17:06
text name: undefined
INFO
17:06
snapshot name: Joao Pedro
Solved!
i already tried useState before, but i think i did something wrong, but now its working well!
const [name, setName] = useState("teste");
const [email, setEmail] = useState("email");
firebase.database().ref('users/' + firebase.auth().currentUser.uid + '/profile').once("value")
.then( (snapshot) => {
setName(snapshot.val().name)
setEmail(snapshot.val().email)
})

Register and push data to Firebase in React Native

I have a registers and push data to Firebase function. I have a problem that when two functions are nested they are registered and stored in Firebase but there are warnings (below). But when I delete the push data function, there is no warning. I want to be able to register and be able to save data. Or can I write two separate functions and when onPress can call two functions at the same time?
This is my code:
handleSignUp = () => {
const { username, email, passwordOne } = this.state;
const { history } = this.props;
auth.doCreateUserWithEmailAndPassword(email, passwordOne)
.then(authUser => {
// Create a user in your own accessible Firebase Database too
db.doCreateUser(authUser.user.uid, username, email)
.then(() => {
this.setState({ ...INITIAL_STATE }, () => {
history.navigation.navigate("MainScreenNavigator");
});
})
.catch(error => this.setState({ errorMessage: error.message }));
})
.catch(error => this.setState({ errorMessage: error.message }));
};
And warning:
Warning: Can't call setState (or forceUpdate) 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 the componentWillUnmount method.
doCreactUser function
export const doCreateUser = (id, username, email) =>
db.ref(`users/${id}`).set({
username,
email,
});
Full code:
import React, { Component } from "react";
import {
StyleSheet,
Text,
View,
StatusBar,
TextInput,
TouchableOpacity,
KeyboardAvoidingView
} from "react-native";
import Logo from "../components/Logo";
import { Actions } from "react-native-router-flux";
import { auth, db, firebase } from "../firebase/";
const INITIAL_STATE = {
username: "",
email: "",
passwordOne: "",
passwordTwo: "",
errorMessage: null
};
export default class Signup extends Component<{}> {
constructor(props) {
super(props);
this.state = { INITIAL_STATE };
}
handleSignUp = () => {
const { username, email, passwordOne } = this.state;
const { history } = this.props;
auth.doCreateUserWithEmailAndPassword(email, passwordOne)
.then(authUser => {
// Create a user in your own accessible Firebase Database too
db.doCreateUser(authUser.user.uid, username, email)
.then(() => {
this.setState({ ...INITIAL_STATE }, () => {
history.navigation.navigate("MainScreenNavigator");
});
})
.catch(error => this.setState({ errorMessage: error.message }));
})
.catch(error => this.setState({ errorMessage: error.message }));
};
goBack() {
Actions.pop();
}
render() {
const {
username,
email,
passwordOne,
passwordTwo,
} = this.state;
const isInvalid =
passwordOne !== passwordTwo ||
passwordOne === "" ||
email === "" ||
username === "";
const display = isInvalid ? "none" : "flex";
return (
<View style={styles.container}>
<StatusBar backgroundColor="#99d066" barStyle="light-content" />
<Logo />
<KeyboardAvoidingView>
<TextInput
style={styles.inputBox}
underlineColorAndroid="rgba(0,0,0,0)"
placeholder="Full Name"
placeholderTextColor="#000"
autoCapitalize="none"
selectionColor="#fff"
keyboardType="default"
onSubmitEditing={() => this.passwordOne.focus()}
onChangeText={username => this.setState({ username })}
value={this.state.username}
/>
<TextInput
style={styles.inputBox}
underlineColorAndroid="rgba(0,0,0,0)"
placeholder="Email"
placeholderTextColor="#000"
autoCapitalize="none"
selectionColor="#fff"
keyboardType="email-address"
onSubmitEditing={() => this.passwordOne.focus()}
onChangeText={email => this.setState({ email })}
value={this.state.email}
/>
<TextInput
style={styles.inputBox}
underlineColorAndroid="rgba(0,0,0,0)"
placeholder="Password"
secureTextEntry={true}
placeholderTextColor="#000"
autoCapitalize="none"
ref={input => (this.passwordOne = input)}
onChangeText={passwordOne => this.setState({ passwordOne })}
value={this.state.passwordOne}
/>
<TextInput
style={styles.inputBox}
underlineColorAndroid="rgba(0,0,0,0)"
placeholder="Confirm Password"
secureTextEntry={true}
placeholderTextColor="#000"
autoCapitalize="none"
ref={input => (this.passwordTwo = input)}
onChangeText={passwordTwo => this.setState({ passwordTwo })}
value={this.state.passwordTwo}
/>
</KeyboardAvoidingView>
<TouchableOpacity style={[styles.button, { display }]}>
<Text style={styles.buttonText} onPress={this.handleSignUp}>
Sign up
</Text>
</TouchableOpacity>
{this.state.errorMessage && (
<Text style={{ color: "#b71c1c", textAlign: "center" }}>
{this.state.errorMessage}
</Text>
)}
<View style={styles.signupTextCont}>
<Text style={styles.signupText}>Already have an account?</Text>
<TouchableOpacity onPress={this.goBack}>
<Text
style={styles.signupButton}
onPress={() => this.props.navigation.navigate("Login")}
>
{" "}
Sign in
</Text>
</TouchableOpacity>
</View>
</View>
);
}
}
const styles = StyleSheet.create({...});

Resources