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.
Related
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
This is my sign out function which should redirect the user to the login screen after logout. But it is not working and I am getting the error "nothing was returned from this render".
const signout= async() => {
setShowLoading(true);
try {
const a= await auth().signOut().then(()=>{
console.log(a);
setUser(null)
setShowLoading(true)
if(!user)
{
return navigation.navigate('Login')
}
}
);
}
catch (e) {
setShowLoading(false);
Alert.alert(
e.message
);
}
};
and this is my return in function
return (
<View style={{ flex: 1, alignItems: 'center', justifyContent: 'center' }}>
<Text>Welcome {user.email}</Text>
<Button title="logout" onPress={()=>signout()}/>
{showLoading &&
<View style={styles.activity}>
<ActivityIndicator size="large" color="#0000ff" />
</View>
}
</View>
);
Nothing was returned from render function means, that one of you Components has nothing returned to it to render. In your codeblock's case, in a case where there is user, nothing is being returned. Either you edit renderMethod to return Home screen or you can navigate user to a different page before user is set or unset depending on your requirement. Either way, react must have something to render to the screen or it will throw an error like this.
this might not be an issue with the mapping itself but i've read some data from my firebase realtime database into my sate and i'm trying to pass it as props then map it in a subsequent component.
I am getting the following error, I am using an android emulator:
TypeError: undefined is not a function (near ...'this.props.notes.map'...)
app.js (where I update the state)
state = {
loggedin: false,
notes: [
{
id: 1,
text: "mow the lawn",
author: "dean",
time: "10am"
},
{
id: 2,
text: "feed the dog",
author: "sam",
time: "2pm"
}
]
}
//passing props to notes component
<Notes style={styles.notes} notes={this.state.notes} />
updateNotes = async () => {
console.log("grabbing new notes");
const snapshot = await firebase.database().ref('Users/Notes').once('value');
console.log(snapshot.val())
this.setState({ notes: snapshot.val() });
};
my Notes component where I map the props
renderCondition =()=>{
if(this.state.Deleted === false){
return(
<View>
{this.props.notes.map(note => (
<View
style={styles.note}
key={note.author}
id={note.id}
>
<Text style={styles.noteHeader}>{note.author}</Text>
<Text style={styles.noteText}>{note.text}</Text>
<Text style={styles.noteTime}>{note.time}</Text>
<Button title= 'X' onPress={() => this.setState({Deleted:true}) }></Button>
</View>
))}
</View>
)
}
return(
<View>
<Text>are you sure you want to delete this note?</Text>
<Button title="Yes"></Button>
<Button onPress ={()=>{this.setState({Deleted:false})}} title="No"></Button>
</View>
)
}
render() {
return (
<View>
{this.renderCondition()}
</View>
);
}
You have to check whether the notes have been passed down or whether they are undefined or null. JavaScript is not going to map an undefined object.
Try the following code:
{this.props.notes && this.props.notes.map(note => (
// do stuff with each note...
))}
This will run the .map function only if the notes are neither undefined nor null.
So my issue was that I needed to update my notes state by making sure it was an array. I had mistakenly simply updated it as an object and then attempted to map the object. Here is my solution.
from this
updateNotes = async () => {
console.log("grabbing new notes");
const snapshot = await firebase.database().ref('Users/Notes').once('value');
console.log(snapshot.val())
this.setState({ notes: snapshot.val() });
};
to this
updateNotes = async () => {
console.log("grabbing new notes");
const snapshot = await firebase.database().ref('Users/Notes').once('value');
console.log(snapshot.val())
this.setState({ notes: [snapshot.val()] });
};
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);
});
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