In react native with firebase I get a chat app code. It used a button to show my registered friends, but I want to check when this button click user is logged in or not.
This is the button code in render function
render() {
return (
<View style={styles.containerl}>
<StatusBar barStyle="light-content" backgroundColor="red" />
<TouchableOpacity>
<Text
style={styles.buttonStyle}
onPress={() => this.props.navigation.navigate("Friendlist")}
>
SHOW FRIEND LIST
</Text>
</TouchableOpacity>
</View>
);
}
I want to add this firebase authentication code in to Show Friend List text press.
firebase.auth().onAuthStateChanged((user) => {
if (user) {
console.log('user logged')
}
});
Can anyone help me?
You can do like below. Add a flag to check whether the user logged in or not
state = {
isUserLogged: false
}
constructor(props) {
super(props);
firebase.auth().onAuthStateChanged((user) => {
if (user) {
this.setState({
isUserLogged: true
})
} else {
this.setState({
isUserLogged: false
})
}
});
}
render() {
return (
<View style={styles.containerl}>
<StatusBar barStyle="light-content" backgroundColor="red" />
<TouchableOpacity>
<Text
style={styles.buttonStyle}
onPress={() => {
if (this.state.isUserLogged) {
this.props.navigation.navigate("Friendlist")
} else {
console.log('user not logged')
}
}
}
>
SHOW FRIEND LIST
</Text>
</TouchableOpacity>
</View>
);
}
In order to show whether a user is logged in or not, you'll need to attach a variable to the user state. So, your authentication code:
firebase.auth().onAuthStateChanged((user) => {
if (user) {
console.log('user logged')
}
});
essentially, will put this method in either the constructor() or the componentDidMount() method.
From there, you'll need to set the state, like -
firebase.auth().onAuthStateChanged((user) => {
if (user) {
this.setState({ userLoggedIn: true });
console.log('user logged')
}
});
and in your render() you can attach conditions to this.state.userLoggedIn on your onPress() method accordingly.
If you need to send the logged in state to your <Friendlist/> component, you'll be required to do -
this.props.navigation.navigate("Friendlist", {userLoggedIn: this.state.userLoggedIn})
and in your <Friendlist/> component you can fetch it from this.props.navigation.state.params.userLoggedIn
Related
I'm using useEffect to retrieve some user and group data on initial screen load on a react-native app. The following code for this is here:
const [groupInfo, setGroupInfo] = useState([]);
//Called on INITIAL rendering
useEffect(() => {
async function getGroupData() {
let groupCode = '';
//Retrieve group code from user
await getDoc(doc(db, 'users', email)).then(userSnapshot => {
if (userSnapshot.exists()) {
groupCode = userSnapshot.data()['group_code'];
}
else { console.log('No user with that email exists!'); }
}).catch(err => {
console.log(err);
});
//Retrieve group information from user
await getDoc(doc(db, 'groups', groupCode)).then(groupSnapshot => {
if (groupSnapshot.exists()) {
setGroupInfo(groupSnapshot.data());
}
else { console.log('No group with that code exists!'); }
}).catch(err => {
console.log(err);
});
}
getGroupData();
}, [email]);
The problem is that when I've tried to render this on my return statement, I get an error. I've logged my data before and that has worked fine but it seems that the app loads the view first. THe following react render code and error are below:
return (
<View style={styles.container}>
<View style={styles.header}>
<Text style={styles.headerLeft}>Goals</Text>
<Text style={styles.headerRight}>Week of 11/20/22</Text>
</View>
<Text style={styles.prize}>Prize: Winner gets a free starbucks drink!</Text>
{/*<View style={styles.goalBox}>
<Text>Workout 3x per week</Text>
<CheckBox style={styles.checkbox}/>
</View> */}
{/* TODO edit prize screen */}
<Button title="Edit prize" />
<View style={styles.memberHeader}>
<Text style={styles.headerLeft}>Members</Text>
<Text style={styles.numMembers}>4</Text>
</View>
{
groupInfo['members'].map((memberName, index) =>
<View style={styles.member}>
<Text style={styles.memberText}>{memberName}</Text>
</View>
)
}
<Button title="Invite member" />
</View>
);
Error:
ERROR TypeError: Cannot read property 'map' of undefined
This error is located at:
in ScreenViewGroup (created by SceneView)
EDIT:
So I think the problem is that at the same time the component is being rendered, the data is being loaded in. I'm still receiving the same error but I've noticed that when I edit my code, the data gets loaded in automatically.
Text strings also seem to render in properly as well but just not the array.
So I found a work-around. By declaring my initial array with values, React will fill those values in as default values and immediately change them to the firebase values when they load.
I'm building a barcode reader app that scans that qr code and then takes data and is used as a key to fetch an object from firebase. In order the data to be used as a key I need to pass through another screen but when I check console log it's cameback that the scanned key is undefined.
The itself barcode scanner works perfectly.
Barcode class :
export class BarCodeScannerScreen extends Component{
state = {
CameraPermissionGranted: null,
}
async componentDidMount() {
// Ask for camera permission
const { status } = await Permissions.askAsync(Permissions.CAMERA);
this.setState({ CameraPermissionGranted: status === "granted" ? true : false });
};
barCodeScanned = ({ data }) => {
//Access the Data
alert(data); // shows the scanned key
this.props.navigation.navigate('Info', {
item: data, }); // but then it's dissapears in here.
};
render(){
const { CameraPermissionGranted } = this.state;
if(CameraPermissionGranted === null){
// Request Permission
return(
<View style={styles.container}>
<Text>Please grant Camera permission</Text>
</View>
);
}
if(CameraPermissionGranted === false){
// Permission denied
return (
<View style={styles.container}>
<Text>Camera Permission Denied.</Text>
</View>
);
}
if(CameraPermissionGranted === true){
// Got the permission, time to scan
return (
<View style = {{
flex: 1,
justifyContent: 'center',
alignItems: 'center',
}}>
<BarCodeScanner
onBarCodeScanned = {this.barCodeScanned }
style = {{
height: DEVICE_HEIGHT/1.1,
width: DEVICE_WIDTH,
}}
>
</BarCodeScanner>
</View>
);
}
}
}
Here is my Info screen that receives the information :
export default class InfoScreen extends Component {
constructor(props){
super(props);
this.state={
productlist:[],
scannedkey: this.props.route.params.item
} }
async componentDidMount(){
firebase.database().ref(`product/${ this.state.scannedkey}`).on(
"value",
(snapshot) => {
var list = [];
snapshot.forEach((child) => {
list.push({
key: child.key,
title: child.val().title,
//details: child.val().details,
//price: child.val().price
});
});
this.setState({ productlist: list });
},
(error) => console.error(error)
);
}
componentWillUnmount() {
if (this.valuelistener_) {
this.valueRef_.off("value", this.valuelistener_)
}}
render() {
console.log(this.state.scannedkey); // console log shows that scanned key is undefined
return(
<View style={styles.container}>
<Text>Hey</Text>
<Text>{this.state.productlist.title}</Text>
</View>
);}}
App.js
export default function App() {
const Drawer=createDrawerNavigator();
return (
<Provider store={store}>
<NavigationContainer>
<Drawer.Navigator initialRouteName="Barcode">
<Drawer.Screen name="Barcode" component={BarCodeScannerScreen} />
<Drawer.Screen name="Info" component={InfoScreen} />
</Drawer.Navigator>
</NavigationContainer>
</Provider>
);
}
I ussualy use function components to navigate through but with class components it's a little tricky for me. Perhaps I missed something?
So far I 've tried :
this.props.navigation.navigate('Info', {
item: JSON.stringify(data) , });
And it didn't work.
I will be grateful for your help.
Try to use item directly from props, not from state
in your componentDidMount call where you supply from state the scannedKey, supply it from props
firebase.database().ref(`product/${this.props.route.params.item}`)....
you are also calling this.props instead of props directly in your state inside your constructor, which have direct access to it, that's why you can call super(props) and not super(this.props), I am not sure if this is the issue, but in react docs says don't copy props to state because they get ignored, and it's bad practice my friend.
check this link, in the big yellow note what I am reffering to
https://reactjs.org/docs/react-component.html#constructor
I have a simple component that checks if the user is logged in or not.
20% of the times this works correctly, but the other 80%, the page is just loading forever as firebase.auth().onAuthStateChanged is never fired or it is fired after minutes of loading.
What could be happening?
class Loading extends Component {
componentDidMount() {
this.checkIfLoggedIn();
}
checkIfLoggedIn = () => {
console.warn("checking if logged in")
firebase.auth().onAuthStateChanged(
user => {
console.warn('AUTH STATE CHANGED CALLED ', user)
if (user) {
console.log("there is indeed a user")
this.props.navigation.navigate('Main');
} else {
console.log("go authenticate")
this.props.navigation.navigate('Auth');
}
}
);
};
render() {
return (
<View style={styles.container}>
<Text>Please wait there</Text>
<ActivityIndicator size="large" />
</View>
);
}
}
I figured it out. I was navigating to an unexisting component.
I have created phone number verify screen and now I want to integrate firebase-auth for verifying phone number via OTP. But I have no idea how to do that, Please help me with it.
I have tried to find tutorial and example, but those were not helpful for me.
Phone Verify Screen
import React from 'react';
import {StyleSheet, View, TextInput, TouchableOpacity, Text, KeyboardAvoidingView, BackHandler, Alert, AsyncStorage, ToastAndroid } from 'react-native';
import HandleBack from '../component/backHandler';
import * as firebase from 'firebase';
class BuyerVerify extends React.Component{
componentDidMount(){
this.getData();
};
onBack = () => {
return true;
};
getData = () => {
const getNumber = async () => {
let number = '';
try {
number = await AsyncStorage.getItem('number');
} catch (error) {
// Error retrieving data
console.log(error.message);
}
//return number;
alert(number);
}
getNumber();
};
render(){
return(
<HandleBack onBack={this.onBack}>
<View style={styles.root}>
<View style={styles.outer}>
<View style={styles.inner}>
<KeyboardAvoidingView style={styles.container}>
<TextInput style={styles.input}
placeholder="Enter OTP"
placeholderTextColor="#939eaf"
keyboardType="phone-pad"
/>
<TouchableOpacity style={styles.button1Container}>
<Text style={styles.buttonText}>
Verify Buyer
</Text>
</TouchableOpacity>
<TouchableOpacity style={styles.button2Container} onPress={()=> this.props.navigation.navigate('Main')}>
<Text style={styles.buttonText}>
Change number
</Text>
</TouchableOpacity>
</KeyboardAvoidingView>
</View>
</View>
</View>
</HandleBack>
);
}
}
export default BuyerVerify;
I want to verify phone number via OTP using firebase.
From Firebase's PhoneAuthProvider interface:
// 'recaptcha-container' is the ID of an element in the DOM.
var applicationVerifier = new firebase.auth.RecaptchaVerifier(
'recaptcha-container');
var provider = new firebase.auth.PhoneAuthProvider();
provider.verifyPhoneNumber('+16505550101', applicationVerifier)
.then(function(verificationId) {
var verificationCode = window.prompt('Please enter the verification ' +
'code that was sent to your mobile device.');
return firebase.auth.PhoneAuthProvider.credential(verificationId,
verificationCode);
})
.then(function(phoneCredential) {
return firebase.auth().signInWithCredential(phoneCredential);
});
I could retrieve data from Firebase and display it immediately after. But when I try to use it in render, it is blank. I am new to react-native and might be doing something incorrect. How can I use data from Firebase in render ?
Here is my code:
componentWillMount() {
firebase.database().ref('/users/' + userId).once('value').then(function(snapshot) {
var DisplayEmail = snapshot.val().Email; alert(DisplayEmail);
});
}
render() {
return (
{alert(this.props.DisplayEmail)}
<TextInput style={styles.input}
autoFocus = {true}
autoCorrect = {false}
autoCapitalize = "none"
placeholder={this.DisplayEmail}
keyboardType="email-address"
underlineColorAndroid='transparent'
editable={false}
/>
)
}
Whenever you want to have something display on render, you should put it on state. By changing the state, you would cause the page to re-render and be updated with the new state. So when you do your firebase call, add it to state.
componentWillMount() {
firebase.database().ref('/users/' + userId).on('value', snapshot => {
this.setState({ DisplayEmail: snapshot.val().Email });
});
}
Calling set state just merges your state changes with your current state. Now you should be able to call state from render and have it work.
render() {
return (
{alert(this.props.DisplayEmail)}
<TextInput style={styles.input}
autoFocus={true}
autoCorrect={false}
autoCapitalize="none"
placeholder={this.state.DisplayEmail}
keyboardType="email-address"
underlineColorAndroid='transparent'
editable={false}
/>
)
}
it must be work :)
componentWillMount() {
firebase.database().ref('/users/' + userId)
.on('value', snapshot => {
this.state = { DisplayEmail: snapshot.val().Email
});
}
render() {
return (
{alert(this.props.DisplayEmail)}
<TextInput style={styles.input}
autoFocus = {true}
autoCorrect = {false}
autoCapitalize = "none"
placeholder={this.state.DisplayEmail}
keyboardType="email-address"
underlineColorAndroid='transparent'
editable={false}
/>
)
}