Expo location not have address module - reactjs

I'm trying to get current location for my project but it's giving me this error even I installed expo-location
Can someone help me fix this error?
Thank you so much

Remove <Location.Address>
Final Output:
Here is the full working example.
Use your own Maps API Key to use reverseGeocodeAsync.
import React, { useEffect, useState } from 'react';
import { Text, View, StyleSheet, TouchableOpacity } from 'react-native';
import Constants from 'expo-constants';
// You can import from local files
import AssetExample from './components/AssetExample';
let apiKey = 'YOUR_API_KEYS';
// or any pure javascript modules available in npm
import { Card } from 'react-native-paper';
import * as Location from 'expo-location';
export default function App() {
const [location, setLocation] = useState(null);
const [errorMsg, setErrorMsg] = useState(null);
const [address, setAddress] = useState(null);
const [getLocation, setGetLocation] = useState(false);
useEffect(() => {
(async () => {
let { status } = await Location.requestPermissionsAsync();
if (status !== 'granted') {
setErrorMsg('Permission to access location was denied');
}
Location.setGoogleApiKey(apiKey);
console.log(status);
let { coords } = await Location.getCurrentPositionAsync();
setLocation(coords);
console.log(coords);
if (coords) {
let { longitude, latitude } = coords;
let regionName = await Location.reverseGeocodeAsync({
longitude,
latitude,
});
setAddress(regionName[0]);
console.log(regionName, 'nothing');
}
// console.log();
})();
}, [getLocation]);
return (
<View style={styles.container}>
<Text style={styles.big}>
{!location
? 'Waiting'
: `Lat: ${location.latitude} \nLong: ${
location.longitude
} \n${JSON.stringify(address?.["subregion"])}`}
</Text>
<TouchableOpacity onPress={() => setGetLocation(!getLocation)}>
<View
style={{
height: 100,
backgroundColor: 'teal',
justifyContent: 'center',
alignItems: 'center',
borderRadius: 10,
marginTop: 20,
}}>
<Text style={styles.btnText}> GET LOCATION </Text>
</View>
</TouchableOpacity>
</View>
);
}
const styles = StyleSheet.create({
container: {
flex: 1,
backgroundColor: 'white',
alignItems: 'center',
justifyContent: 'center',
},
big: {
fontSize: 18,
color: 'black',
fontWeight: 'bold',
},
btnText: {
fontWeight: 'bold',
fontSize: 25,
color: 'white',
},
});
You can play with the working code here: Expo Link

Related

How to make Toggle Button with Animated.View in React Native?

I can only use react native in the project, I need to make a Toggle Component with AnimatedView. I tried with react native switcher but it won't be responsive for mobile and web at the same time.
Here is my code
export const ToggleButton = () => {
const [isEnabled, setIsEnabled] = useState(false);
const [text, setText] = useState('');
const toggleSwitch = () => {
if (isEnabled) {
setText('OFF');
} else {
setText('ON');
}
setIsEnabled(previousState => !previousState);
};
return (
<View style={styles.container}>
<View>
{isEnabled ? <Text style={styles.textOn}>On</Text> : <Text style={styles.textOff}>Off</Text>}
<Switch
trackColor={{ false: Colors.BlueLight, true: Colors.PurpleLight }}
thumbColor={isEnabled ? Colors.BlueLight : Colors.BlueLight}
ios_backgroundColor="#3E3E3E"
onValueChange={toggleSwitch}
value={isEnabled}
/>
</View>
</View>
);
};
Someone give me a recommendation how to do it?
Hye finally i made a custom switch, do check out :
Do check out this expo https://snack.expo.dev/#gaurav1995/gnarly-sandwich
Its completely built with react native, no external libraries etc
Do lemme know in case of any doubts :)
import React, { useState, useRef } from 'react';
import {
Text,
View,
StyleSheet,
Animated,
TouchableOpacity,
Easing
} from 'react-native';
export default function App() {
const positionButton = useRef(new Animated.Value(0)).current;
const [isOn, setIsOn] = useState(false);
const startAnimToOff = () => {
Animated.timing(positionButton,{
toValue:0,
duration:500,
easing:Easing.ease
}).start()
};
const startAnimToOn = () => {
Animated.timing(positionButton,{
toValue:1,
duration:500,
easing:Easing.ease
}).start()
};
const positionInterPol = positionButton.interpolate({inputRange:[0,1],outputRange:[0,30]})
const backgroundColorAnim = positionButton.interpolate({inputRange:[0,1],outputRange:["#767577","#81b0ff"]})
const initialOpacityOn = positionButton.interpolate({inputRange:[0,1],outputRange:[0,1]})
const initialOpacityOff = positionButton.interpolate({inputRange:[0,1],outputRange:[1,0]})
const onPress = () => {
if (isOn) {
startAnimToOff();
setIsOn(false);
} else {
startAnimToOn();
setIsOn(true);
}
};
return (
<View style={styles.container}>
<TouchableOpacity style={{height:30,width:60}} activeOpacity={0.9} onPress={onPress} >
<Animated.View style={[styles.mainStyes,{
backgroundColor:backgroundColorAnim
}]} >
<Animated.Text
style={[
styles.eahcStyles,
{
opacity: initialOpacityOn,
},
]}>
ON
</Animated.Text>
<Animated.Text
style={[
styles.eahcStylesOf,
{
opacity: initialOpacityOff,
},
]}>
OFF
</Animated.Text>
<Animated.View style={[styles.basicStyle,{
transform:[{
translateX:positionInterPol
}]
}]} />
</Animated.View>
</TouchableOpacity>
</View>
);
}
const styles = StyleSheet.create({
container: {
flex: 1,
justifyContent: 'center',
backgroundColor: '#ecf0f1',
padding: 8,
},
basicStyle: {
height: 20,
width: 20,
borderRadius: 20,
backgroundColor: '#FFF',
marginTop: 5,
marginLeft: 5,
},
eahcStyles: {
fontSize: 14,
color: '#f5dd4b',
position: 'absolute',
top: 6,
left: 5,
},
eahcStylesOf: {
fontSize: 14,
color: '#f4f3f4',
position: 'absolute',
top: 6,
right: 5,
},
mainStyes: {
borderRadius: 30,
backgroundColor: '#81b0ff',
height: 30,
width: 60,
},
paragraph: {
margin: 24,
fontSize: 18,
fontWeight: 'bold',
textAlign: 'center',
},
});

Why useState is not working in React Native? [duplicate]

This question already has answers here:
The useState set method is not reflecting a change immediately
(15 answers)
Closed 10 months ago.
I am getting an error that I do not understand in the application I developed in React Native Expo. The error is as follows; In asyncstorage I keep the name of the user logged into the application. But when I try to set it while the page is loading (useEffect), setLastUser doesn't work. When I do CTRL+S on the keyboard while trying on the same page, I get the following output.
Prev CTRL+S
After CTRL+S
Can you help me? Thanks.
App.js Code
import { StatusBar } from 'expo-status-bar';
import React, { useState, useMemo } from 'react';
import { StyleSheet, Text, View } from 'react-native';
import { NavigationContainer } from '#react-navigation/native';
import { createNativeStackNavigator } from '#react-navigation/native-stack';
import SignIn from './SignIn';
import SignUp from './SignUp';
import Conversation from './Conversation';
import Contacts from './Contacts';
import Settings from './Settings';
import Chats from './Chats';
import { createBottomTabNavigator } from '#react-navigation/bottom-tabs';
import {Ionicons} from '#expo/vector-icons'
import { UserProvider } from './UserContext';
import { LogBox } from "react-native"
const Stack = createNativeStackNavigator();
const Tabs = createBottomTabNavigator();
const TabsNavigator = () => (
<Tabs.Navigator screenOptions={({ route }) => ({
tabBarIcon: ({ focused, color, size }) => {
return <Ionicons name={route.name === "Chats" ? "chatbubble-ellipses-outline" : route.name === "Contacts" ? "people-outline" : "settings-outline"} color={color} size={size} />
}})}>
<Tabs.Screen name="Chats" component={Chats} />
<Tabs.Screen name="Contacts" component={Contacts} />
<Tabs.Screen name="Settings" component={Settings} />
</Tabs.Navigator>
);
export default function App() {
LogBox.ignoreAllLogs(true);
// const [lastUser, setLastUser] = useState('none');
// const value = useMemo(
// () => ({ lastUser, setLastUser }),
// [lastUser]
// );
return (
<UserProvider>
<NavigationContainer>
<Stack.Navigator>
<Stack.Screen options={{headerShown : false }} name="SignIn" component={SignIn} />
<Stack.Screen
name="SignUp"
component={SignUp}
options={{ headerTitle:'Login', headerBackVisible : true, headerBackTitleVisible :true}}
/>
<Stack.Screen name="Home" component={TabsNavigator} options={{headerShown : false, headerBackTitleVisible : false}}/>
<Stack.Screen name="Contacts" component={Contacts} options={{ headerTitle:'ChatApp'}}/>
<Stack.Screen name="Conversation" component={Conversation} options={{ headerTitle:'ChatApp'}}/>
</Stack.Navigator>
</NavigationContainer>
</UserProvider>
);
}
const styles = StyleSheet.create({
container: {
flex: 1,
backgroundColor: '#fff',
alignItems: 'center',
justifyContent: 'center',
},
});
SignIn.js code
import { useNavigation } from '#react-navigation/core'
import React, { useEffect, useState, createContext, useContext } from 'react'
import { KeyboardAvoidingView, StyleSheet, Text, TextInput, TouchableOpacity, View, Image } from 'react-native'
import { borderColor } from 'react-native/Libraries/Components/View/ReactNativeStyleAttributes'
import { auth, firebase } from './firebase'
import { userContext } from './UserContext'
import AsyncStorage from '#react-native-async-storage/async-storage';
const SignIn = () => {
const [email, setEmail] = useState('')
const [password, setPassword] = useState('')
const navigation = useNavigation()
const value = useContext(userContext);
const handleLogin = async() => {
await auth
.signInWithEmailAndPassword(email, password)
.then(userCredentials => {
const user = userCredentials.user;
console.log('Logged in with:', user.email);
getUser(user.email);
navigation.replace("Home");
})
.catch(error => alert(error.message))
}
const getUser = async (email2) => {
await firebase.database().ref().child('users').orderByChild('email').equalTo(email2).once('value').then((data) => {
data.forEach((node) => {
storeUser(node.val().username); // one data
}
)
}
)
}
const storeUser = async(data) => {
try{
await AsyncStorage.setItem('sertacKul', data);
}catch(err){
console.log(err);
}
}
return(
<KeyboardAvoidingView
style={styles.container}
behavior="padding"
>
<View style={styles.inputContainer}>
<Image style={styles.logo} source={require('./img/logo.png')}>
</Image>
<TextInput
placeholder="Email"
value={email}
onChangeText={text => setEmail(text)}
style={styles.input}
/>
<TextInput
placeholder="Password"
value={password}
onChangeText={text => setPassword(text)}
style={styles.input}
secureTextEntry
/>
</View>
<View style={styles.buttonContainer}>
<TouchableOpacity
onPress={handleLogin}
style={styles.button}
>
<Text style={styles.buttonText}>Login</Text>
</TouchableOpacity>
<TouchableOpacity
//onPress={handleSignUp}
onPress={() => navigation.navigate('SignUp')}
style={[styles.button, styles.buttonOutline]}
>
<Text style={styles.buttonOutlineText}>Register</Text>
</TouchableOpacity>
<TouchableOpacity
//onPress={handleSignUp}
onPress={() => value.setData('ebebbebebe')}
style={[styles.button, styles.buttonOutline]}
>
<Text style={styles.buttonOutlineText}>{value.lastUser}</Text>
</TouchableOpacity>
</View>
</KeyboardAvoidingView>
)
}
export default SignIn;
const styles = StyleSheet.create({
container: {
flex: 1,
justifyContent: 'center',
alignItems: 'center',
backgroundColor : 'white'
},
logo :{
resizeMode :'contain',
width: '100%',
marginBottom : 40
},
inputContainer: {
width: '80%'
},
input: {
backgroundColor: '#eeeeee',
paddingHorizontal: 15,
paddingVertical: 10,
borderRadius: 10,
marginTop: 5,
},
buttonContainer: {
width: '60%',
justifyContent: 'center',
alignItems: 'center',
marginTop: 40,
},
button: {
backgroundColor: '#06d6cc',
width: '100%',
padding: 15,
borderRadius: 10,
alignItems: 'center',
},
buttonOutline: {
backgroundColor: 'white',
marginTop: 5,
borderColor: '#06d6cc',
borderWidth: 2,
},
buttonText: {
color: 'white',
fontWeight: '700',
fontSize: 16,
},
buttonOutlineText: {
color: '#06d6cc',
fontWeight: '700',
fontSize: 16,
},
})
Contact.js code
import React, { useState, useEffect, useContext } from "react";
import {
StyleSheet,
View,
TextInput,Text
} from "react-native";
import { auth, firebase } from "./firebase";
import { List, Avatar, Divider, FAB } from "react-native-paper";
import uuid from "react-native-uuid";
import moment from "moment";
import { userContext } from "./UserContext";
import AsyncStorage from '#react-native-async-storage/async-storage';
const Contacts = () => {
const [username, setUsername] = useState("");
const value = useContext(userContext);
const [contactList, setContactList] = useState([{}]);
const [lastUser, setLastUser] = useState('');
useEffect(() => {
setContactList([])
setLastUser(() => getUserName()) // ıs not work
console.log('deneme',lastUser)
getContacts();
}, [])
async function getUserName(){
let user = await AsyncStorage.getItem('sertacKul');
return user;
}
const addFriend = () => {
console.log(value.lastUser)
firebase
.database()
.ref("/users/")
.once("value")
.then((data) => {
let id = uuid.v4();
firebase
.database()
.ref("/friendrelations/" + id)
.set({
id: id,
user1: username,
user2: lastUser,
relationtype: "normal",
createdDate: moment().format("DD/MM/YYYY HH:mm:ss"),
})
.then(() => alert("Friend added."));
});
};
const getContacts = async() => {await firebase.database().ref().child('friendrelations').orderByChild('user2').equalTo(() => getUserName())
.once('value').then(data => {
data.forEach((node) => { setContactList(lastContacts => [...lastContacts, node.val().user1])})
})}
return (
<View>
<TextInput
placeholder="Yeni Arkadaş"
value={username}
style={styles.input}
onChangeText={(text) => setUsername(text)}
/>
<FAB
onPress={() => addFriend()}
icon="plus"
style={{ position: "absolute", right: 16 }}
/>
{/*
BURASI BURASI BURASI BURASI BURASI BURASI BURASI BURASI BURASI BURASI
{contactList && contactList.map((item)=>{
return( <List.Item onPress={() => navigation.navigate('Conversation')} title={item}
left={() => <Avatar.Image source={require('./img/profile1.png')} size={53}/>}
/>
)
})} */}
<Divider inset/>
</View>
);
};
export default Contacts;
const styles = StyleSheet.create({
container: {
flex: 1,
justifyContent: "center",
alignItems: "center",
backgroundColor: "white",
},
logo: {
resizeMode: "contain",
width: "100%",
marginBottom: 40,
},
inputContainer: {
width: "80%",
},
input: {
backgroundColor: "#eeeeee",
paddingHorizontal: 15,
paddingVertical: 10,
borderRadius: 10,
marginTop: 5,
},
buttonContainer: {
width: "60%",
justifyContent: "center",
alignItems: "center",
marginTop: 40,
},
button: {
backgroundColor: "#06d6cc",
width: "100%",
padding: 15,
borderRadius: 10,
alignItems: "center",
},
buttonOutline: {
backgroundColor: "white",
marginTop: 5,
borderColor: "#06d6cc",
borderWidth: 2,
},
buttonText: {
color: "white",
fontWeight: "700",
fontSize: 16,
},
buttonOutlineText: {
color: "#06d6cc",
fontWeight: "700",
fontSize: 16,
},
});
You have to await the response of getUserName function. A good option is place the content of useEffect inside a async function. For example:
useEffect(() => {
setContactList([]);
updateLastUserName();
getContacts();
}, []);
useEffect(() => {
// Need to wait the lastUser state change to can use it
console.log(lastUser);
}, [lastUser]);
async function updateLastUserName(){
const username = await getUserName();
setLastUser(username);
}
async function getUserName(){
const user = await AsyncStorage.getItem('sertacKul');
return user;
}

Unable to figure out the source of the error - react native

I am developing react-native app for quite sometimes. During my development, almost everyday i am facing some error/warning. Among them, the most comment error I've faced is this-> Warning: Can't perform a React state update on an unmounted component. I've searched everywhere, but couldn't find a proper solution. And this log also not explaining that much. So is there anyone who can explain this which will be much more understandable, or point me out where should I dig into to solve this error or what more should I study to understand the situation. Here is the full screenshot of this error.
. And Here is the some code of one of my component:
//packages
import React, { useContext, useEffect, useState } from 'react';
import { ActivityIndicator, ImageBackground, Pressable, StyleSheet, Text, View } from 'react-native';
// third pirty packages
import { Button, HamburgerIcon, Menu, NativeBaseProvider, useToast } from 'native-base';
import Feather from 'react-native-vector-icons/Feather';
import Foundation from "react-native-vector-icons/Foundation";
import NetInfo from "#react-native-community/netinfo";
import {
widthPercentageToDP as wp,
heightPercentageToDP as hp,
listenOrientationChange as lor,
removeOrientationListener as rol
} from 'react-native-responsive-screen';
//assets and components
import { AuthContext } from './../context';
const MainBody = (props) => {
const { signOut } = useContext(AuthContext);
const [isLoading, setIsLoading] = useState(false);
const toast = useToast();
useEffect(() => {
lor();
return () => {
rol();
};
}, []);
const styles = StyleSheet.create({
wrapperView: {
height: hp('87%'),
paddingTop: hp('7%'),
alignItems: 'center',
backgroundColor: '#fff'
},
dashboardView: {
width: '80%',
display: 'flex',
flexDirection: 'row',
justifyContent: 'space-between',
marginBottom: hp('3%')
},
dashboardCategory: {
width: '45%',
height: hp('20%'),
borderRadius: 5,
elevation: 5,
display: 'flex',
flexDirection: 'column',
justifyContent: 'center',
backgroundColor: '#FFFFFF'
},
iconStyle: {
color: 'grey',
fontSize: hp('5%'),
alignSelf: 'center'
},
buttonText: {
marginTop: 10,
color: '#4b2e80',
width: '100%',
textAlign: 'center',
fontSize: hp('2.7%')
},
headerButtonView: {
position: 'absolute',
top: hp('3%'),
right: wp('5%')
}
});
return (
<View>
<View style={styles.wrapperView}>
<View style={styles.dashboardView}>
<Button light style={styles.dashboardCategory}>
<Feather style={styles.iconStyle} name="users" />
<Text style={styles.buttonText}> Clip </Text>
</Button>
<Button light style={styles.dashboardCategory}>
<Foundation style={styles.iconStyle} name='pound' />
<Text style={styles.buttonText}> Balancing </Text>
</Button>
</View>
</View>
<View style={styles.headerButtonView}>
<Menu
trigger={(triggerProps) => {
return (
<Pressable accessibilityLabel="More options menu" {...triggerProps}>
<HamburgerIcon color="#fff" />
</Pressable>
)
}}
>
<Menu.Item onPress={() => signOut()}>Logout</Menu.Item>
</Menu>
</View>
</View>
);
}
export const DashboardScreen = ({ navigation }) => {
return (
<NativeBaseProvider>
<MainBody navigate={navigation.navigate} />
</NativeBaseProvider>
);
}
we need to unsubscribe the particular subscription before our components unmounts. it's a workaround but will get rid of the error.
useEffect(() => {
let mounted = true
if(mounted){
lor();
}
return () => {
rol();
mounted= false
};
}, []);

how can i get data from firebase in descending order

//this is my accounts.js where i am fetching accounts from user node in user node and pass to the card.js component where every account prints in cards with accounttitle and accountbalance . but when i take snapshot of one user's accounts they are fetched in ascending order but i want to get accounts from firebase in descending order how can i do this.this is my database structure in firebase
import React, { useState, useEffect } from "react";
import { Fontisto } from "#expo/vector-icons";
import Firebase from "../components/Firebase";
import { StyleSheet, Text, View, TouchableOpacity } from "react-native";
import Cards from "../components/Accounts/Cards";
import AddAccountModal from "../components/Accounts/AddAccountModal";
import FundTransferModal from "../components/Accounts/FundTransferModal";
export default function AccountsScreen() {
let add = {
id: 111,
title: "Add",
backgroundColor: "#fff",
};
let [total, setTotal] = useState(0);
let [accounts, setAccount] = useState([]);
const [backgroundColor, setbackgroundColor] = useState("#ff7f50");
const [addAccountmodal, SetAddAccountmodal] = useState(false);
const [fundModal, setFundModal] = useState(false);
const showAddmodal = () => {
SetAddAccountmodal(true);
};
const closeAddmodal = () => {
setbackgroundColor("#ff7f50");
SetAddAccountmodal(false);
};
const showFundModal = () => {
setFundModal(true);
};
const closeFundModal = () => {
setFundModal(false);
};
useEffect(() => {
let user = Firebase.auth().currentUser;
let uid = user.uid;
Firebase.database()
.ref("users/" + uid)
.child("accounts")
.on("value", (snapshot) => {
let tempAccounts = [];
let temptotal = 0;
snapshot.forEach(function (snapshotAccount) {
let account = {
id: snapshotAccount.key,
title: snapshotAccount.val().title,
balance: snapshotAccount.val().balance,
backgroundColor: snapshotAccount.val().backgroundColor,
};
let balance = parseFloat(account.balance, 10);
temptotal = temptotal + balance;
tempAccounts.push(account);
});
tempAccounts.push(add);
setTotal(temptotal);
setAccount(tempAccounts);
});
}, []);
return (
<View style={styles.container}>
<AddAccountModal
addAccountmodal={addAccountmodal}
closeAddmodal={closeAddmodal}
backgroundColor={backgroundColor}
setbackgroundColor={setbackgroundColor}
/>
<FundTransferModal
fundModal={fundModal}
closeFundModal={closeFundModal}
/>
<View style={styles.headingContent}>
<Text style={styles.heading}>Accounts</Text>
<View style={styles.balanceContent}>
<Text style={styles.heading}>Total: </Text>
<Text style={styles.balance}>+ Rs.{total}</Text>
<View style={styles.icon}>
{/* <TouchableOpacity onPress={() => showFundModal()}>
<Fontisto name="arrow-swap" size={25} color="#29416F" />
</TouchableOpacity> */}
</View>
</View>
</View>
<Cards accounts={accounts} showAddmodal={showAddmodal} />
</View>
);
}
const styles = StyleSheet.create({
container: {
flex: 1,
backgroundColor: "#fff",
},
headingContent: {
marginTop: 10,
paddingTop: 10,
paddingHorizontal: 21,
width: "100%",
height: 50,
flexDirection: "row",
justifyContent: "space-between",
},
balanceContent: {
flexDirection: "row",
},
heading: {
color: "#333",
fontWeight: "bold",
fontSize: 16,
},
balance: {
color: "green",
fontWeight: "bold",
fontSize: 16,
},
icon: {
flexDirection: "row",
justifyContent: "flex-end",
marginLeft: "5%",
justifyContent: "center",
},
});
We can use orderBy event to get data in asc or desc order.
For Example: citiesRef.orderBy("name", "desc"),
Reference: https://firebase.google.com/docs/firestore/query-data/order-limit-data

Im new to react and I am having a ton of issues trying to get data fields from firestore to show up on the screen on my app

I am going to include photos as well as my code. I do not know what I am doing wrong but I wanna be able to print the current user's name on their profile page as shown in pictures. Thanks so much! It seems as if it is never getting to the snapshot to try to retrieve the fields to where they can be used. I've been stuck on this for going on a week now and do not know what else to try. I feel like it is an easy fix that I am missing but cannot pinpoint what it is.
Firestore picture
App picture
import 'react-native-gesture-handler';
import auth, {firebase} from '#react-native-firebase/auth';
import firestore from '#react-native-firebase/firestore';
//import * as React from 'react';
import React, {useState} from 'react';
import {NavigationContainer} from '#react-navigation/native';
import {
StyleSheet,
Picker,
SafeAreaView,
Text,
View,
TextInput,
TouchableOpacity,
Button,
} from 'react-native';
import {createStackNavigator} from '#react-navigation/stack';
import {ScrollView} from 'react-native-gesture-handler';
const Profile = ({navigation}) => {
const [firstName, setFname] = useState('');
const [lastName, setLname] = useState('');
const [email, setEmail] = useState('');
const [password, setPassword] = useState('');
const [age, setAge] = useState('');
const [sex, setSex] = useState('');
const [id, setId] = useState('');
getUserInfo = async () => {
firebase
.firestore()
.collection('users')
.doc(firebase.auth().currentUser.uid)
.onSnapshot((docs) => {
setFname(docs.data().firstName);
console.log(firstName);
setLname({lastName: docs.data().lastName});
setEmail({email: docs.data().email});
setPassword({password: docs.data().password});
setAge({age: docs.data().age});
setSex({sex: docs.data().sex});
setId({id: docs.data().id});
});
};
const db = firebase.firestore();
var user = firebase.auth().currentUser;
var usersEmail = user.email;
var userID = firebase.auth().currentUser.uid;
db.collection('users')
.where('email', '==', usersEmail)
.get()
.then(function (querySnapshot) {
querySnapshot.forEach(function (doc) {
// doc.data() is never undefined for query doc snapshots
console.log(doc.id, ' => ', doc.data());
var data = doc.data();
const fn = doc.get('firstName');
setFname({firstName: fn});
console.log(firstName);
console.log(data);
setFname(data.firstName);
//var lastName = data.lastName;
//var firstName = doc.get("first");
//var lastName = doc.get("last");
});
})
.catch(function (error) {
console.log('Error getting documents: ', error);
});
return (
<SafeAreaView style={styles.container2}>
<ScrollView>
<View style={styles.container}>
<Text style={styles.logo}>Profile</Text>
<Text style={styles.Info}>
Name: {firstName} {lastName}
</Text>
<Text style={styles.Info}>Email: {usersEmail}</Text>
<Text style={styles.Info}>Age: </Text>
<Text style={styles.Info}>Sex:</Text>
<Text style={styles.Info}>Sports:</Text>
<TouchableOpacity
style={styles.button}
onPress={() => navigation.navigate('EditProfile')}>
<Text style={styles.buttonText}>Edit Profile</Text>
</TouchableOpacity>
<TouchableOpacity
style={styles.button}
onPress={() => navigation.navigate('Messages')}>
<Text style={styles.buttonText}>My Messages</Text>
</TouchableOpacity>
</View>
</ScrollView>
</SafeAreaView>
);
};
const styles = StyleSheet.create({
container: {
flex: 1,
backgroundColor: '#2c9f45',
alignItems: 'center',
justifyContent: 'center',
},
container2: {
flex: 1,
backgroundColor: '#2c9f45',
justifyContent: 'center',
},
button: {
width: '85%',
backgroundColor: '#263844',
borderRadius: 25,
height: 54,
alignItems: 'center',
justifyContent: 'center',
marginTop: 15,
marginBottom: 15,
},
buttonText: {
color: 'white',
fontSize: 20,
},
logo: {
fontWeight: 'bold',
fontSize: 54,
color: '#263844',
marginBottom: 20,
},
Info: {
fontWeight: 'bold',
fontSize: 22,
color: '#263844',
marginBottom: 20,
},
});
export default Profile;
Its all getting render before the results have been returned, you need include useEffect and run your firebase from within inside the useEffect function.
This is pretty decent blog and will help with the understanding of hooks.
Something like this (untested);
import 'react-native-gesture-handler';
import auth, {firebase} from '#react-native-firebase/auth';
import firestore from '#react-native-firebase/firestore';
//import * as React from 'react';
import React, {useEffect, useState} from 'react';
import {NavigationContainer} from '#react-navigation/native';
import {
StyleSheet,
Picker,
SafeAreaView,
Text,
View,
TextInput,
TouchableOpacity,
Button,
} from 'react-native';
import {createStackNavigator} from '#react-navigation/stack';
import {ScrollView} from 'react-native-gesture-handler';
const Profile = ({navigation}) => {
const [firstName, setFname] = useState('');
// const db = firebase.firestore();
// const { email } = firebase.auth().currentUser;
const email = ‘Sprint3#test.com’;
useEffect( () => {
db.collection('users')
.where('email', '==', usersEmail)
.get()
.then(function (querySnapshot) {
// This will step over every doc that has that email, you should limit it one and organise by an updated field. .limit(1)
querySnapshot.forEach(function (doc) {
const fn = doc.get('firstName');
setFname(fn);
// Add whatever states from the data you need or just one object with all the info in.
});
})
.catch(function (error) {
console.log('Error getting documents: ', error);
});
}, []);
return (
<SafeAreaView style={styles.container2}>
<ScrollView>
<View style={styles.container}>
<Text style={styles.logo}>Profile</Text>
<Text style={styles.Info}>
Name: {firstName}
</Text>
<TouchableOpacity
style={styles.button}
onPress={() => navigation.navigate('EditProfile')}>
<Text style={styles.buttonText}>Edit Profile</Text>
</TouchableOpacity>
<TouchableOpacity
style={styles.button}
onPress={() => navigation.navigate('Messages')}>
<Text style={styles.buttonText}>My Messages</Text>
</TouchableOpacity>
</View>
</ScrollView>
</SafeAreaView>
);
};
const styles = StyleSheet.create({
container: {
flex: 1,
backgroundColor: '#2c9f45',
alignItems: 'center',
justifyContent: 'center',
},
container2: {
flex: 1,
backgroundColor: '#2c9f45',
justifyContent: 'center',
},
button: {
width: '85%',
backgroundColor: '#263844',
borderRadius: 25,
height: 54,
alignItems: 'center',
justifyContent: 'center',
marginTop: 15,
marginBottom: 15,
},
buttonText: {
color: 'white',
fontSize: 20,
},
logo: {
fontWeight: 'bold',
fontSize: 54,
color: '#263844',
marginBottom: 20,
},
Info: {
fontWeight: 'bold',
fontSize: 22,
color: '#263844',
marginBottom: 20,
},
});
export default Profile;

Resources