How to navigate dashboard when login successful in React native? - react-native

I have implemented some code in react native, to connect with the express backend. This only works for all the users without the role == admin. I could able to print the Successfully logged! in console. But now I need to navigate to the dashboard. How can I do that. I don't know how to do that. another thing is in the touchableOpacity I saw the attribute called value. But I can't find the meaning of that. Please help me in this regard. Also I have attach the service file also.
import React, {useState} from 'react';
import {
View,
Text,
TouchableOpacity,
TextInput,
StyleSheet,
StatusBar,
Dimensions,
} from 'react-native';
import {useTheme} from '#react-navigation/native';
import * as Animatable from 'react-native-animatable';
import LinearGradient from 'react-native-linear-gradient';
import axios from 'axios';
import {hostName} from '../../constants/constants';
import {login} from '../../services/authService';
import AsyncStorage from '#react-native-community/async-storage';
const SigninPage = ({navigation}) => {
const [email, setEmail] = useState('');
const [password, setPassword] = useState('');
const {colors} = useTheme();
const signIn = () => {
login(email, password)
.then((res) => {
// if (res.data.role == 'admin') {
// throw new Error('Cannot login');
// } else {
AsyncStorage.setItem('userData', JSON.stringify(res.data.dbResult[0]));
AsyncStorage.setItem('userRole', res.data.role);
AsyncStorage.setItem('userToken', res.data.token);
console.log('successfully logged!');
// }
})
.catch((err) => {
console.log(err);
});
};
return (
<View style={{flex: 1, backgroundColor: '#000e60'}}>
<StatusBar backgroundColor="#009387" barStyle="light-content" />
<View style={styles.header}>
<Animatable.Image
animation="bounceIn"
duraton="1500"
source={require('../../assets/img/afisolve_logo.png')}
style={styles.logo}
resizeMode="stretch"
/>
</View>
<Animatable.View
style={[
styles.footer,
{
backgroundColor: colors.background,
},
]}
animation="fadeInUpBig">
<Text style={styles.signinTop}>Sign in with your account</Text>
<View style={styles.inputView}>
<TextInput
style={styles.TextInput}
placeholder="Email"
placeholderTextColor="white"
onChangeText={(email) => setEmail(email)}
/>
</View>
<View style={styles.inputView}>
<TextInput
style={styles.TextInput}
placeholder="Password"
placeholderTextColor="white"
secureTextEntry={true}
onChangeText={(password) => setPassword(password)}
/>
</View>
<TouchableOpacity onPress={() => signIn()}>
<LinearGradient colors={['#730018', '#00085b']} style={styles.signIn}>
<Text style={styles.textSign}>SIGN IN</Text>
</LinearGradient>
</TouchableOpacity>
<Text>Fogot Your Password?</Text>
</Animatable.View>
</View>
);
};
export default SigninPage;
const {height} = Dimensions.get('screen');
const height_logo = height * 0.28;
const styles = StyleSheet.create({
header: {
flex: 2,
justifyContent: 'center',
alignItems: 'center',
},
logo: {
width: height_logo,
height: height_logo,
borderRadius: 150 / 3,
},
footer: {
flex: 1,
backgroundColor: '#fff',
borderTopLeftRadius: 30,
borderTopRightRadius: 30,
paddingVertical: 50,
paddingHorizontal: 30,
alignItems: 'center',
justifyContent: 'center',
},
inputView: {
backgroundColor: '#2937f6',
width: '70%',
height: 45,
marginBottom: 20,
alignItems: 'center',
},
textSign: {
color: 'white',
fontWeight: 'bold',
},
signIn: {
width: 150,
height: 40,
justifyContent: 'center',
alignItems: 'center',
borderRadius: 50,
flexDirection: 'row',
},
signinTop: {
color: '#000000',
fontSize: 20,
fontWeight: 'bold',
paddingBottom: 25,
},
});
Service file
import axios from 'axios';
import {hostName} from '../constants/constants';
export const login = (email, password) => {
return axios.post(hostName + '/authentication/login', {
email: email,
password: password,
});
};

this may help you
const signIn = () => {
login(email, password)
.then((res) => {
// if (res.data.role == 'admin') {
// throw new Error('Cannot login');
// } else {
AsyncStorage.setItem('userData', JSON.stringify(res.data.dbResult[0]));
AsyncStorage.setItem('userRole', res.data.role);
AsyncStorage.setItem('userToken', res.data.token);
console.log('successfully logged!');
//here
navigation.replace('Home');//if you don't wanna call login back
//else
navigation.navigate('Home');
// }
})
.catch((err) => {
console.log(err);
});
};

I use this tutorial to implement the Authentication flows.
Basically, you retrieve your access token, then store it in redux/context. Your Navigator detects that the user has an access token and change the screens available.

I have found a good answer to my question. If someone got the same stuck, will help you following the corrected issue.
const signIn = () => {
login(email, password)
.then((res) => {
// if (res.data.role == 'admin') {
// throw new Error('Cannot login');
// } else {
AsyncStorage.setItem('userData', JSON.stringify(res.data.dbResult[0]));
AsyncStorage.setItem('userRole', res.data.role);
AsyncStorage.setItem('userToken', res.data.token);
console.log('successfully logged!');
navigation.navigate('Home');
// }
})
.catch((err) => {
console.log(err);
});
};

Related

Stream chat message input not calculating keyboard height properly until you type

For some reason, only on android, the keyboard compatible view with stream chat doesn't calculate the proper height correctly until I start to type. I have tried many different configurations and can't figure out why it is only on android and why it readjusts as soon as I start to type.
Here is the code for the chat.
import "react-native-gesture-handler";
import {
StyleSheet,
Text,
View,
Pressable,
KeyboardAvoidingView,
Platform,
Dimensions,
StatusBar,
Keyboard,
} from "react-native";
import { useHeaderHeight } from "#react-navigation/elements";
import React, { useState, useContext, useEffect } from "react";
import Header from "../components/Header";
import { StreamChat } from "stream-chat";
import {
SafeAreaView,
useSafeAreaInsets,
SafeAreaProvider,
} from "react-native-safe-area-context";
import { GestureHandlerRootView } from "react-native-gesture-handler";
import { ChatContext } from "../../contexts/ChatContext";
import {
Channel,
Chat,
MessageInput,
MessageList,
OverlayProvider,
ChannelList,
Thread,
} from "stream-chat-expo";
import { Ionicons } from "#expo/vector-icons";
import { getAuth } from "firebase/auth";
import { doc, getDoc } from "firebase/firestore";
import { db } from "../../firebase";
import { UserContext } from "../../contexts/UserContext";
import ChatProfileView from "../components/ChatProfileView";
const client = StreamChat.getInstance(api-key);
const auth = getAuth();
const ChatScreen = () => {
const { channel, setChannel } = useContext(UserContext);
const [chatContactVisible, setChatContactVisible] = useState(false);
const [chatContactToView, setChatContactToView] = useState({});
const [thread, setThread] = useState(null);
const [userName, setUserName] = useState(null);
const [chatName, setChatName] = useState(null);
const [chatId, setChatId] = useState(null);
const [keyboardHeight, setKeyboardHeight] = useState(0);
const { bottom } = useSafeAreaInsets();
const headerHeight = useHeaderHeight();
useEffect(() => {
if (!client.user) {
getStreamUserToken().then((userToken) => {
client.connectUser(
{
id: auth.currentUser.uid,
},
userToken.data
);
console.log("loggeduserin- login");
});
}
}, []);
const clearChannel = () => {
setChannel();
setChatName();
setChatContactToView();
};
const clearThread = () => {
setThread(null);
};
useEffect(() => {
console.log(channel);
}, [channel, setChannel]);
const theme = {
messageList: {
container: {
backgroundColor: "white",
},
},
channelPreview: {
container: { backgroundColor: "white" },
},
};
useEffect(() => {
async function getUserNames() {
const userRef = doc(db, "users", auth.currentUser.uid);
const docSnap = await getDoc(userRef);
if (docSnap.exists()) {
const info = docSnap.data();
setUserName(info.firstName);
}
}
getUserNames();
}, []);
const getUserData = async () => {
const userRef = doc(db, "users", chatId);
const docSnap = await getDoc(userRef);
if (docSnap.exists()) {
const info = docSnap.data();
setChatContactToView(info);
console.log(info);
}
};
useEffect(() => {
if (channel) {
if (userName === channel.data.memberOne) {
setChatName(channel.data.memberTwo);
setChatId(channel.data.memberTwoId);
console.log("---------- id set");
console.log(channel.data.memberTwoId);
} else {
setChatName(channel.data.memberOne);
setChatId(channel.data.memberOneId);
console.log("---------- id set now");
console.log(channel.data.memberTwoId);
}
}
}, [channel, setChannel]);
const CustomPreviewTitle = ({ channel }) => {
if (userName === channel.data.memberOne) {
return <Text>{channel.data.memberTwo}</Text>;
} else {
return <Text>{channel.data.memberOne}</Text>;
}
};
const openChatContact = () => {
getUserData()
.then(setChatContactVisible(true), console.log("opened"))
.catch((err) => {
alert("User no longer exists :(");
});
};
const filters = { members: { $in: [auth.currentUser.uid] } };
return (
<ChatContext.Provider
value={{
chatContactVisible,
setChatContactVisible,
chatContactToView,
setChatContactToView,
}}
>
<GestureHandlerRootView style={styles.container}>
<SafeAreaView style={{ flex: 1 }}>
<Chat client={client} style={theme}>
<Header screenName="Chat" />
{channel ? (
<Channel
channel={channel}
thread={thread}
threadList={!!thread}
keyboardBehavior={"padding"}
keyboardVerticalOffset={0}
>
<View
style={{
justifyContent: "space-between",
flexDirection: "row",
alignItems: "center",
height: 40,
}}
>
<View
style={{
marginLeft: 10,
flexDirection: "row",
justifyContent: "center",
alignItems: "center",
}}
>
<Pressable onPress={clearChannel}>
<Ionicons
name="arrow-back-sharp"
size={30}
color="black"
/>
</Pressable>
<Pressable onPress={openChatContact}>
<Text
style={{
color: "black",
fontSize: 20,
marginLeft: 10,
}}
>
{chatName}
</Text>
</Pressable>
</View>
{thread ? (
<Pressable
style={{
marginRight: 15,
}}
onPress={clearThread}
>
<Text style={{ color: "#3b55d9" }}>Close thread</Text>
</Pressable>
) : (
<></>
)}
</View>
{thread ? (
<Thread />
) : (
<>
<MessageList onThreadSelect={setThread} />
<MessageInput />
</>
)}
</Channel>
) : (
<View style={styles.scroll}>
<ChannelList
onSelect={setChannel}
filters={filters}
PreviewTitle={CustomPreviewTitle}
style={theme}
/>
</View>
)}
</Chat>
{chatContactVisible ? <ChatProfileView /> : <></>}
</SafeAreaView>
</GestureHandlerRootView>
</ChatContext.Provider>
);
};
export default ChatScreen;
const styles = StyleSheet.create({
container: {
flex: 1,
flexDirection: "column",
backgroundColor: "white",
},
scroll: {
flex: 9,
},
});
`
Here is the code for the header component.
`import { StyleSheet, Text, View, Pressable } from "react-native";
import React, { useState, useEffect, useContext } from "react";
import { auth } from "../../firebase";
import { useNavigation } from "#react-navigation/core";
import { Ionicons } from "#expo/vector-icons";
import { StreamChat } from "stream-chat";
import { UserContext } from "../../contexts/UserContext";
import { getDocs, query, where, collection } from "firebase/firestore";
import { getAuth } from "firebase/auth";
import { db } from "../../firebase";
import { LikesContext } from "../../contexts/LikesContext";
import ProfileView from "./Likes";
const client = StreamChat.getInstance(api-key);
const Header = (props) => {
const [likesVisible, setLikesVisible] = useState(false);
const { tempLikesArray, setTempLikesArray } = useContext(UserContext);
const navigation = useNavigation();
const handleSignOut = () => {
auth
.signOut()
.then(async () => {
navigation.replace("Login");
await client.disconnectUser();
console.log("User disconnected");
})
.catch((error) => alert(error.mesage));
};
const openLikes = () => {
setLikesVisible(true);
};
return (
<LikesContext.Provider
value={{
likesVisible,
setLikesVisible,
}}
>
<View style={styles.header}>
<Text style={styles.logoText}>{props.screenName}</Text>
<View style={{ flexDirection: "row" }}>
<Pressable
style={{ justifyContent: "center", marginRight: 15 }}
onPress={openLikes}
>
<View
style={[
tempLikesArray.length > 0
? styles.likeBubbleVisible
: styles.likeBubbleInvisible,
]}
></View>
<Ionicons name="ios-person-add-outline" size={24} color="black" />
</Pressable>
<Pressable
style={{ justifyContent: "center", marginRight: 15 }}
onPress={handleSignOut}
>
<Ionicons name="ios-log-out-outline" size={24} color="black" />
</Pressable>
</View>
{likesVisible ? <ProfileView /> : <></>}
</View>
</LikesContext.Provider>
);
};
export default Header;
const styles = StyleSheet.create({
header: {
flex: 1,
flexDirection: "row",
flexWrap: "wrap",
backgroundColor: "white",
width: "100%",
justifyContent: "space-between",
marginTop: 10,
},
logoText: {
alignSelf: "center",
fontSize: 30,
color: "#3b55d9",
marginLeft: 20,
fontFamily: "Inter_900Black",
},
logoutButton: {
alignSelf: "center",
},
image: {
width: 20,
height: 20,
alignSelf: "center",
marginRight: 20,
},
likeBubbleVisible: {
width: 5,
height: 5,
borderRadius: 10,
backgroundColor: "blue",
position: "absolute",
display: "flex",
top: 2,
left: 0,
},
likeBubbleInvisible: {
width: 5,
height: 5,
backgroundColor: "blue",
position: "absolute",
display: "none",
top: 2,
left: 0,
},
});
`

Looped TextInput have the copy each other

this may sound stupid for the most of you but I'm new when it comes to using API and react native. My situation is the next. From my data I try to display questions and a text field so the customer can answer and therefore I retrieve the data. But my problem is the next on when I display and try to write in the TextInput no matter how I have they will all copy what I write in which ever one I'm writing on. I don't get what I am doing wrong. I tried with looping but I can't seem to get the right answer to solve my problem. Here's my code if someone can help me.
//import liraries
import React, { Component, useEffect, useState } from 'react';
import {
View,
Text,
StyleSheet,
FlatList,
TextInput,
Picker,
} from 'react-native';
// create a component
const Get = ({ navigation }) => {
const [user, setUser] = useState();
// const [text, onChangeText] = React.useState(null);
const [selectedValue, setSelectedValue] = useState("Test");
const [text, onChangeText] = useState('');
const getUserData = async () => {
try {
let response = await fetch('https://survey-back-nmucl6ui6q-ey.a.run.app/survey/7b504f09-7a67-4f99-a402-c15a9388446c', {
headers: new Headers({
'Authorization': 'eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJleHAiOjE2NTUxNTU1MjMsImlhdCI6MTY1NTA2OTExOCwic3ViIjoxfQ.eoLaDT4wP99yjC38DN2Zck2sgwXFvcRYrfzxszHkQvc',
'Content-Type': 'application/x-www-form-urlencoded'
}),
});
let json = await response.json();
console.log(json.question)
setUser(json.question);
} catch (error) {
console.error(error);
}
};
useState(() => {
getUserData();
}, []);
const renderItem = ({ item }) => {
return (
<View
style={{
borderBottomWidth: 1,
borderBottomColor: '#ccc',
padding: 5,
}}>
{item.question_type == 'text-field' ?
<View style={styles.questions}>
<Text style={styles.label}>{item.name}</Text>
<TextInput
style={styles.input}
onChangeText={onChangeText}
value={text}
placeholder="Entrez votre réponse"
/>
</View>
: <Text>Erreur</Text>}
{item.question_type == 'select' ?
<View style={styles.questions}>
<Text style={styles.label}>{item.name}</Text>
<Picker
selectedValue={selectedValue}
onValueChange={(itemValue, itemIndex) =>
setSelectedValue(itemValue)}
>
{Object.keys(item.choice).map(key =>{
return (
<Picker.Item label={key} value={key} key={key} />
)
})}
</Picker>
</View>
: <Text style={{display: 'none'}}>Erreur</Text>}
<View>
{item.question_type == 'comboboxMulti' ?
<Text style={{ fontWeight: 'bold' }}>{item.name}</Text>
: <Text style={{display: 'none'}}>Ça marche pas</Text>}
</View>
</View>
);
};
return (
<View style={styles.container}>
<FlatList
data={user}
renderItem={renderItem}
keyExtractor={(item) => item.id}
/>
</View>
);
};
// define your styles
const styles = StyleSheet.create({
container: {
flex: 1,
justifyContent: 'center',
alignItems: 'center',
backgroundColor: '#fff',
},
input: {
height: 40,
margin: 12,
borderWidth: 1,
padding: 10,
borderRadius: 5,
marginLeft: 0,
},
label: {
textTransform: 'capitalize',
},
questions: {
justifyContent: 'center',
alignItems: 'start',
}
});
//make this component available to the app
export default Get;

login screen is coming once then after few seconds goes off where i have done mistake please tell me

Below is my code where i am checking if user data set in asyncstorage it will check from asyncstorage if asyncstorage having value then move to drawer navigation.
import React, {useState, useEffect,createRef} from 'react';
import {
StyleSheet,
TextInput,
View,
Text,
ScrollView,
Image,
Keyboard,
TouchableOpacity,
KeyboardAvoidingView,
} from 'react-native';
import DrawerNavigationRoutes from './DrawerNavigationRoutes';
import axios from 'react-native-axios/lib/core/Axios';
import AsyncStorage from '#react-native-community/async-storage';
import Loader from './Components/Loader';
import { renderNode } from 'react-native-elements/dist/helpers';
const baseUrl = 'http://3.108.170.236/erp/apis/login_otp.php';
const LoginScreen = ({navigation}) => {
console.log('Starting--------------------------------------------------------------------');
const CheckUserSignedIn = async () => {
let context = this;
try {
let value = await AsyncStorage.getItem('Otp_details');
if (value != null)
{
// do something
console.log('User mobile Otp verified');
setUserLoggedin(true);
navigation.replace('DrawerNavigationRoutes');
return null;
}
else
{
// LoginScreen;
// return null;
}
} catch (error) {
// Error retrieving data
}
};
const [userEmail, setUserEmail] = useState('');
const [userMobile, setUserMobile] = useState('');
const [userOtp, setUserOtp] = useState('');
const [userPassword, setUserPassword] = useState('');
const [loading, setLoading] = useState(false);
const [errortext, setErrortext] = useState('');
const [sendOtp, setSendOtp] = useState('Send OTP');
const [myText, setMyText] = useState('My Original Text');
const [studentID, setStudentID] = useState('');
const [showTheThing, setshowTheThing] = useState(false);
const [userLoggedin,setUserLoggedin] = useState(false);
const [otpData, setOtpData] = useState([]);
const [myotp_value,setMyotp_value] = useState('');
const [mystudent_id,setMystudent_id]=useState('');
const [resend_otp,setResend_otp] = useState(false);
const passwordInputRef = createRef();
const otpInputRef = createRef();
const handleSubmitPress = async () => {
const userdetails= await AsyncStorage.getItem("Otp_details");
const details = JSON.parse(userdetails);
const otp_valued = details[0].otp_value;
const student_idd = details[0].student_id;
setMyotp_value('123');
setMyotp_value(otp_valued);
setMystudent_id(student_idd);
console.log(myotp_value);
console.log(userOtp);
if(myotp_value==userOtp){
console.log('OTP verified');
navigation.replace('DrawerNavigationRoutes');
return null;
}
else
{
console.log('otp mismatched');
}
};
const handleasync_copy = async () => {
// navigation.replace('DrawerNavigationRoutes');
// return;
if(!userMobile || userMobile==''|| userMobile==null){
console.log('empty');
alert('Please enter your mobile number');
return;
}
setSendOtp('Resend OTP');
setLoading(true);
const requestOptions = {
method: 'post',
headers: {
Accept: 'application/json',
'Content-Type': 'application/json',
},
body: JSON.stringify({monumber: userMobile}),
};
const response = await fetch(
'http://3.108.170.236/erp/apis/login_otp.php',
requestOptions,
);
//const response1 = await fetch('https://webhook.site/4326abbc-7ec9-41d0-b967-ad888f79c33a',
requestOptions);
console.log('Otp fetched');
const json_data = await response.json();
console.log(json_data);
setLoading(false);
setshowTheThing(true);
await AsyncStorage.setItem("Otp_details", JSON.stringify(json_data));
};
useEffect(() => {
CheckUserSignedIn();
}, []);
if(userLoggedin) {
navigation.replace('DrawerNavigationRoutes');
return null
}
else{
return (
<View style={styles.mainBody}>
<Loader loading={loading} />
<ScrollView
keyboardShouldPersistTaps="handled"
contentContainerStyle={{
flex: 1,
justifyContent: 'center',
alignContent: 'center',
}}>
<View>
<KeyboardAvoidingView enabled>
<View style={{alignItems: 'center'}}>
<Image
source={require('./Image/aboutreact.png')}
style={{
width: '50%',
height: 100,
resizeMode: 'contain',
margin: 30,
}}
/>
</View>
<View style={styles.SectionStyle}>
<TextInput
style={styles.inputStyle}
onChangeText={userMobile => setUserMobile(userMobile)}
placeholder="Enter Mobile Number" //dummy#abc.com
placeholderTextColor="#8b9cb5"
autoCapitalize="none"
keyboardType="numeric"
returnKeyType="next"
onSubmitEditing={() =>
passwordInputRef.current && passwordInputRef.current.focus()
}
underlineColorAndroid="#f000"
blurOnSubmit={false}
maxLength={10}
/>
</View>
<TouchableOpacity
style={styles.buttonStyle}
activeOpacity={0.5}
onPress={handleasync_copy}>
<Text onPress={handleasync_copy} style={styles.buttonTextStyle}>
{sendOtp}
</Text>
</TouchableOpacity>
{showTheThing && (
<View style={styles.SectionStyle}>
<TextInput
style={styles.inputStyle}
onChangeText={userOtp => setUserOtp(userOtp)}
placeholder="Enter OTP" //12345
placeholderTextColor="#8b9cb5"
keyboardType="numeric"
ref={otpInputRef.current && otpInputRef.current.focus()}
onSubmitEditing={Keyboard.dismiss}
blurOnSubmit={false}
secureTextEntry={true}
underlineColorAndroid="#f000"
returnKeyType="next"
maxLength={6}
/>
</View>
)}
{errortext != '' ? (
<Text style={styles.errorTextStyle}> {errortext} </Text>
) : null}
{showTheThing && (
<TouchableOpacity
style={styles.buttonStyle}
activeOpacity={0.5}
onPress={handleSubmitPress}>
<Text style={styles.buttonTextStyle}>Verify and login</Text>
</TouchableOpacity>
)}
</KeyboardAvoidingView>
</View>
</ScrollView>
</View>
);
}
};
export default LoginScreen;
const styles = StyleSheet.create({
mainBody: {
flex: 1,
justifyContent: 'center',
backgroundColor: '#ffffff',
alignContent: 'center',
},
SectionStyle: {
flexDirection: 'row',
height: 40,
marginTop: 20,
marginLeft: 35,
marginRight: 35,
margin: 10,
},
buttonStyle: {
backgroundColor: '#7DE24E',
borderWidth: 0,
color: '#FFFFFF',
borderColor: '#7DE24E',
height: 40,
alignItems: 'center',
borderRadius: 30,
marginLeft: 35,
marginRight: 35,
marginTop: 20,
marginBottom: 25,
},
buttonTextStyle: {
color: '#FFFFFF',
paddingVertical: 10,
fontSize: 16,
},
inputStyle: {
flex: 1,
color: 'black',
paddingLeft: 15,
paddingRight: 15,
borderWidth: 1,
borderRadius: 30,
borderColor: '#dadae8',
},
registerTextStyle: {
color: '#000000',
textAlign: 'center',
fontWeight: 'bold',
fontSize: 14,
alignSelf: 'center',
padding: 10,
},
errorTextStyle: {
color: 'red',
textAlign: 'center',
fontSize: 14,
},
});
This is login screen component. developers please tell me where i am doing mistake login screen is showing once when already logged in user.

How to save image in a Phone on clicking in React Native Expo Camera?

This is what so far I have done. Here I am able to switch ON the camera and also get access to images using ImagePicker. But while clicking image, I am getting anything like where the image is saved and also I am unable to select the image properly.
When I click pic on camera, I get this in console:
"Object {
"height": 4000,
"uri": "file:///data/user/0/host.exp.exponent/cache/ExperienceData/%2540himanshu717171%252FMyProject/Camera/373e905c-2ef8-4f0f-b4a4-78ac8a64732c.jpg",
"width": 3000,
}"
And while selecting any image from Phone, I am getting this response in a console:
"Object {
"cancelled": false,
"height": 721,
"type": "image",
"uri": "file:/data/user/0/host.exp.exponent/cache/ExperienceData/%2540himanshu717171%252FMyProject/ImagePicker/937bed14-dc51-4786-8836-09965b17d327.jpg",
"width": 1280,
}"
This is my code. Please suggest me any changes required.
import React from 'react';
import { StyleSheet, Text, View ,TouchableOpacity,Platform, } from 'react-native';
import { Camera } from 'expo-camera';
import * as Permissions from 'expo-permissions';
import { FontAwesome, Ionicons,MaterialCommunityIcons } from '#expo/vector-icons';
import * as ImagePicker from 'expo-image-picker';
export default class App extends React.Component {
state = {
hasPermission: null,
cameraType: Camera.Constants.Type.back,
}
async componentDidMount() {
this.getPermissionAsync()
}
getPermissionAsync = async () => {
// Camera roll Permission
if (Platform.OS === 'ios') {
const { status } = await Permissions.askAsync(Permissions.CAMERA_ROLL);
if (status !== 'granted') {
alert('Sorry, we need camera roll permissions to make this work!');
}
}
// Camera Permission
const { status } = await Permissions.askAsync(Permissions.CAMERA);
this.setState({ hasPermission: status === 'granted' });
}
handleCameraType=()=>{
const { cameraType } = this.state
this.setState({cameraType:
cameraType === Camera.Constants.Type.back
? Camera.Constants.Type.front
: Camera.Constants.Type.back
})
}
takePicture = async () => {
if (this.camera) {
let photo = await this.camera.takePictureAsync();
console.log(photo);
}
}
pickImage = async () => {
let result = await ImagePicker.launchImageLibraryAsync({
mediaTypes: ImagePicker.MediaTypeOptions.Images
});
console.log(result);
}
render(){
const { hasPermission } = this.state
if (hasPermission === null) {
return <View />;
} else if (hasPermission === false) {
return <Text>No access to camera</Text>;
} else {
return (
<View style={{ flex: 1 }}>
<Camera style={{ flex: 1 }} type={this.state.cameraType} ref={ref => {this.camera = ref}}>
<View style={{flex:1, flexDirection:"row",justifyContent:"space-between",margin:30}}>
<TouchableOpacity
style={{
alignSelf: 'flex-end',
alignItems: 'center',
backgroundColor: 'transparent'
}}
onPress={()=>this.pickImage()}>
<Ionicons
name="ios-photos"
style={{ color: "#fff", fontSize: 40}}
/>
</TouchableOpacity>
<TouchableOpacity
style={{
alignSelf: 'flex-end',
alignItems: 'center',
backgroundColor: 'transparent',
}}
onPress={()=>this.takePicture()}
>
<FontAwesome
name="camera"
style={{ color: "#fff", fontSize: 40}}
/>
</TouchableOpacity>
<TouchableOpacity
style={{
alignSelf: 'flex-end',
alignItems: 'center',
backgroundColor: 'transparent',
}}
onPress={()=>this.handleCameraType()}
>
<MaterialCommunityIcons
name="camera-switch"
style={{ color: "#fff", fontSize: 40}}
/>
</TouchableOpacity>
</View>
</Camera>
</View>
);
}
}
}
App.navigationOptions = {
title: 'Camera',
headerStyle: {
backgroundColor: '#ff6666',
},
headerTintColor: '#fff',
headerTitleStyle: {
fontWeight: 'bold',
fontSize:20
},
};

React-native Undefined is not an object(this.props.navigation.navigate)

I'm attempting to navigate from the login page to the welcome page upon successful login using firebase using a method called submit (located within loginForm). Everything is working with the exception of the navigation, using StackNavigation, to the Welcome page.
I've looked through every post on this error and tried countless fixes using solutions posted all over but can't seem to come up with any fix. I'm sure its a simple and goofy error I'm making here. I would greatly appreciate any help.
(Apologies in advance, this is my first react-native project)
Thank you!
App.js
import React from 'react';
import * as firebase from 'firebase';
import {StackNavigator} from "react-navigation";
import Login from './src/components/Login/Login';
import Welcome from "./src/components/Welcome";
export const AppNavigator = StackNavigator({
Login: {screen: Login},
Welcome: {screen: Welcome},
});
//initialize Firebase
const firebaseConfig = {
apiKey: "************************************",
authDomain: "firstproject-r.firebaseapp.com",
databaseURL: "https://firstproject-r.firebaseio.com",
projectId: "firstproject-r",
storageBucket: "",
messagingSenderId: "************"
};
firebase.initializeApp(firebaseConfig);
class App extends React.Component {
render() {
return (
<AppNavigator/>
);
}
}
export default App;
login.js
import React from 'react';
import {StyleSheet, View, Image, Text, KeyboardAvoidingView, StatusBar}
from 'react-native';
import LoginForm from "./LoginForm";
class Login extends React.Component {
render() {
const { navigate } = this.props.navigation;
return (
<KeyboardAvoidingView behavior='padding' style=
{styles.container}>
<View style={styles.logoContainer}>
<StatusBar barStyle="light-content"/>
<Image
style={styles.logo}
source=
{require('../../images/EquipRentIcon.png')}>
</Image>
<Text style={styles.title}>idostuff</Text>
</View>
<View style={styles.formContainer}/>
<LoginForm/>
</KeyboardAvoidingView>
);
}
}
const styles = StyleSheet.create({
container: {
flex: 1,
backgroundColor: '#3498db',
},
logo: {
width: 160,
height: 160
},
logoContainer: {
alignItems: 'center',
flexGrow: 1,
justifyContent: 'center'
},
title: {
color: '#FFF',
fontSize: 20,
justifyContent: 'center'
},
formContainer: {}
});
export default Login;
loginForm.js
import React from 'react';
import {StyleSheet, Text, View, TextInput, TouchableOpacity, StatusBar} from 'react-native';
import firebase from 'firebase';
// const auth = firebase.auth();
// const fbProvidor = new firebase.auth.FacebookAuthProvider();
// const googProvidor = new firebase.auth.GoogleAuthProvider();
class LoginForm extends React.Component {
constructor(props) {
super(props)
this.submit = this.submit.bind(this);
this.loginUser = this.loginUser.bind(this);
this.createUser = this.createUser.bind(this);
this.state = ({
email: '',
password: '',
navigation: this.props.navigation
})
}
loginUser = (email, password, ) => {
try {
if (this.state.password.length < 6) {
alert("Please enter at least 6 characters")
return;
}
firebase.auth().signInWithEmailAndPassword(email, password).then(function (user) {
console.log(user)
});
this.submit()
}
catch (error) {
console.log(error.toString())
}
};
createUser = (email, password) => {
try {
if (this.state.password.length < 6) {
alert("Please enter at least 6 characters")
return;
}
firebase.auth().createUserWithEmailAndPassword(email, password).then(function () {
});
this.submit()
}
catch (error) {
console.log(error.toString())
}
};
submit() {
this.props.navigation.navigate('Welcome');
}
render() {
return (
<View style={styles.container}>
<StatusBar barStyle="light-content"/>
<TextInput
style={styles.input}
returnKeyType="next"
keyboardType="email-address"
autoCapitalize="none"
autoCorrect={false}
placeholder="username"
onSubmitEditing={() => this.passwordInput.focus()}
onChangeText={(email) => this.setState({email})}
placeholderTextColor="rgba(255, 255, 255, 0.7)">
</TextInput>
<TextInput
style={styles.input}
placeholder="password"
secureTextEntry
returnKeyType="go"
ref={(input) => this.passwordInput = input}
onChangeText={(password) => this.setState({password})}
placeholderTextColor="rgba(255, 255, 255, 0.7)">
</TextInput>
<TouchableOpacity
style={styles.loginButtonContainer}
onPress={() => {
this.loginUser(this.state.email, this.state.password)
}}
>
<Text style={styles.loginButtonText}>
Login
</Text>
</TouchableOpacity>
<TouchableOpacity
style={styles.signupButtonContainer}
onPress={() => {
this.createUser(this.state.email, this.state.password)
}}
>
<Text style={styles.signUpButtonText}>
Sign Up
</Text>
</TouchableOpacity>
</View>
);
}
}
const styles = StyleSheet.create({
container: {
padding: 20
},
input: {
height: 40,
backgroundColor: 'rgba(255, 255, 255, 0.3)',
marginBottom: 15,
fontSize: 20,
paddingHorizontal: 10
},
loginButtonContainer: {
backgroundColor: '#2980b9',
padding: 15,
justifyContent: 'center'
},
signupButtonContainer: {
backgroundColor: 'white',
opacity: .3,
marginTop: 10,
padding: 15,
justifyContent: 'center'
},
loginButtonText: {
textAlign: 'center',
color: 'white',
fontSize: 20,
fontWeight: '700'
},
signUpButtonText: {
textAlign: 'center',
color: 'black',
fontSize: 20,
fontWeight: '700'
}
});
export default LoginForm;
welcome.js
import React from 'react';
import { StyleSheet, Text, View } from 'react-native';
class Welcome extends React.Component{
render() {
const { navigate } = this.props.navigation;
return (
<Text>
this is the welcome screen
</Text>
);
}
}
const styles = StyleSheet.create({
container: {
flex: 1,
backgroundColor: '#3498db',
},
});
export default Welcome;