Could not navigate to another screen when using token in React Native - react-native

I'm currently developing an app using react native, right now my issue is that i couldn't navigate to main screen after login. Below is my code.
This is App.js (EDITED)
import React from 'react';
import { Loading } from './components/common/';
import TabNavigator from './screens/TabNavigator';
import AuthNavigator from './screens/AuthNavigator';
import MainNavigator from './screens/MainNavigator';
import deviceStorage from './services/deviceStorage.js';
import { View, StyleSheet } from 'react-native';
export default class App extends React.Component {
constructor() {
super();
this.state = {
token: '',
loading: true
}
this.newJWT = this.newJWT.bind(this);
this.deleteJWT = deviceStorage.deleteJWT.bind(this);
this.loadJWT = deviceStorage.loadJWT.bind(this);
this.loadJWT();
}
state = {
isLoadingComplete: false,
};
newJWT(token){
this.setState({
token: token
});
}
render() {
if (this.state.loading) {
return (
<Loading size={'large'} />
);
} else if (!this.state.token) {
return (
<View style={styles.container}>
<AuthNavigator screenProps = {{setToken:this.newJWT}} />
</View>
);
} else if (this.state.token) {
return (
<View style={styles.container}>
<MainNavigator screenProps = {{token: this.state.token,
deleteJWT:this.deleteJWT,}} />
</View>
);
}
}
}
This is Login.js (EDITED-v2)
import React, { Component, Fragment } from 'react';
import { Text, View, StyleSheet, ImageBackground, KeyboardAvoidingView,
TouchableOpacity, TextInput, Alert } from 'react-native';
import axios from 'axios';
import deviceStorage from '../services/deviceStorage';
class Login extends Component {
constructor(props) {
super(props)
this.state = {
username: '',
password: '',
error: '',
loading: false
};
this.loginUser = this.loginUser.bind(this);
this.onLoginFail = this.onLoginFail.bind(this);
}
loginUser() {
const { username, password, password_confirmation } = this.state;
this.setState({ error: '', loading: true });
// NOTE Post to HTTPS only in production
axios.post("http://192.168.1.201:8000/api/login",{
username: username,
password: password
})
.then((response) => {
console.log('response',response)
deviceStorage.saveKey("token", response.data.token);
console.log(response.data.token);
this.props.newJWT(response.data.token);
})
.catch((error) => {
const status = error.response.status
if (status === 401) {
this.setState({ error: 'username or password not recognised.' });
}
this.onLoginFail();
//console.log(error);
//this.onLoginFail();
});
}
onLoginFail() {
this.setState({
error: 'Login Failed',
loading: false
});
}
render() {
// other codes here
}
const styles = StyleSheet.create({
// other codes here
});
export { Login };
This is TabNavigator.js (Added)
import React from 'react';
import { Text } from 'react-native';
import { createMaterialTopTabNavigator } from 'react-navigation';
import Ionicons from 'react-native-vector-icons/Ionicons';
import Profile from '../screens/Profile';
const TabNavigator = createMaterialTopTabNavigator(
{
Profile: {
screen: props => <Profile {...props.screenProps} />,
navigationOptions: {
tabBarIcon: ({ tintColor, focused }) => (
<Ionicons
name={focused ? 'ios-person' : 'ios-person'} //TODO change to focused
icon
size={30}
style={{ color: tintColor }}
/>
),
}
},
},
{ initialRouteName: 'Profile',
tabBarPosition: 'top',
swipeEnabled: false,
animationEnabled: true,
lazy: true,
tabBarOptions: {
showLabel: false,
showIcon: true,
activeTintColor: 'orange',
inactiveTintColor: 'orange',
style: {
backgroundColor: '#555',
},
indicatorStyle: {
color: '#orange'
}
}
}
);
const screenTitles = {
Profile: { title: 'Profiler' },
Home: { title: 'Home' },
};
TabNavigator.navigationOptions = ({ navigation }) => {
const { routeName } = navigation.state.routes[navigation.state.index];
const headerTitle = screenTitles[routeName].title;
const tabBarVisible = false;
return {
headerTitle,
tabBarVisible
};
};
export default TabNavigator;
This is my AuthLoadingScreen.js
import React from 'react';
import { View } from 'react-native';
import { Login } from '../screens/Login';
class AuthLoadingScreen extends React.Component {
constructor(props){
super(props);
this.state = {
showLogin: true
};
this.whichForm = this.whichForm.bind(this);
this.authSwitch = this.authSwitch.bind(this);
}
authSwitch() {
this.setState({
showLogin: !this.state.showLogin
});
}
whichForm() {
if(this.state.showLogin){
return(
<Login newJWT={this.props.newJWT} authSwitch={this.authSwitch} />
);
} else {
}
}
render() {
return(
<View style={styles.container}>
{this.whichForm()}
</View>
);
}
}
export default AuthLoadingScreen;
const styles = {
// style codes here
};
Lastly, this is my Profile.js
import React, { Component } from 'react';
import { View, Text, TouchableOpacity, Alert, Platform } from
'react-native';
import { Button, Loading } from '../components/common/';
import axios from 'axios';
export default class Profile extends Component {
constructor(props){
super(props);
this.state = {
loading: true,
email: '',
name: '',
error: ''
}
}
componentDidMount(){
this.onLocationPressed();
const headers = {
'Content-Type': 'application/json',
'Authorization': 'Bearer ' + this.props.token
};
axios({
method: 'GET',
url: 'http://192.168.1.201:8000/api/user',
headers: headers,
}).then((response) => {
console.log('response',response)
console.log('response2',this.props.token)
this.setState({
email: response.data.user.email,
name: response.data.user.name,
loading: false
});
}).catch((error) => {
console.log(error);
this.setState({
error: 'Error retrieving data',
loading: false
});
});
}
render() {
const { container, emailText, errorText } = styles;
const { loading, email, name, error } = this.state;
if (loading){
return(
<View style={container}>
<Loading size={'large'} />
</View>
)
} else {
return(
<View style={container}>
<View>
<Text style={emailText}>Your email: {email}</Text>
<Text style={emailText}>Your name: {name}</Text>
</View>
<Button onPress={this.props.deleteJWT}>
Log Out
</Button>
</View>
);
}
}
}
const styles = {
// style codes here
};
I've fixed the previous problem that couldn't start the app. Right now i can see the login screen, but when i pressed login, there's a yellow box that indicates some problem. I've included the screenshot below.
Lastly i've added the deviceStorage.js
deviceStorage.js
import { AsyncStorage } from 'react-native';
const deviceStorage = {
async saveKey(key, valueToSave) {
try {
await AsyncStorage.setItem(key, valueToSave);
} catch (error) {
console.log('AsyncStorage Error: ' + error.message);
}
},
async loadJWT() {
try {
const value = await AsyncStorage.getItem('token');
if (value !== null) {
this.setState({
token: value,
loading: false
});
} else {
this.setState({
loading: false
});
}
} catch (error) {
console.log('AsyncStorage Error: ' + error.message);
}
},
async deleteJWT() {
try{
await AsyncStorage.removeItem('token')
.then(
() => {
this.setState({
token: ''
})
}
);
} catch (error) {
console.log('AsyncStorage Error: ' + error.message);
}
}
};
export default deviceStorage;
Before navigate
After navigate

This is my setup. It works like a charm. Sorry if it's a bit messy. I removed some stuff for clarity and I may have missed something:
App.js
import React from 'react';
import { Platform, StatusBar, StyleSheet, View } from 'react-native';
import { Asset, Font, Icon } from 'expo';
import { ENDPOINT, USER_TYPE } from './src/config'
import { Loading } from './src/components/common/';
import deviceStorage from './src/services/deviceStorage.js';
import TabNavigator from './src/TabNavigator';
import AuthNavigator from './src/AuthNavigator';
import MainNavigator from './src/MainNavigator';
import globalStyles from './src/globalStyles';
import './ReactotronConfig';
export default class App extends React.Component {
constructor() {
super();
this.state = {
jwt: '',
loading: true,
};
this.newJWT = this.newJWT.bind(this);
this.deleteJWT = deviceStorage.deleteJWT.bind(this);
this.loadJWT = deviceStorage.loadJWT.bind(this);
this.loadJWT();
}
state = {
isLoadingComplete: false,
};
newJWT(jwt) {
this.setState({
jwt: jwt
});
}
render() {
if (this.state.loading) {
return (
<Loading size={'large'} />
);
} else if (!this.state.jwt) {
//console.log(this.props, '<=== app.js');
return (
<View style={styles.container}>
{Platform.OS === 'ios' && <StatusBar barStyle="default" />}
<AuthNavigator screenProps={{setToken: this.newJWT }} />
</View>
);
} else {
return (
<View style={styles.container}>
{Platform.OS === 'ios' && <StatusBar barStyle="default" />}
<MainNavigator
screenProps={{ jwt: this.state.jwt,
deleteToken: this.deleteJWT,
}}
/>
</View>
);
}
}
}
const styles = StyleSheet.create({
container: {
flex: 1,
backgroundColor: '#fff',
justifyContent: 'center',
},
});
AuthNavigator.js
import React from 'react';
import { createAppContainer, createBottomTabNavigator } from 'react-navigation';
import Ionicons from 'react-native-vector-icons/Ionicons';
import AuthScreen from './screens/AuthScreen';
const AuthNavigator = createBottomTabNavigator(
{
Auth: (props) => {
return <AuthScreen {...props.screenProps} />;
}
},
{ initialRouteName: 'Auth',
tabBarOptions: {
showLabel: false,
activeBackgroundColor: '#eee',
}
}
);
export default createAppContainer(AuthNavigator);
MainNavigator.js
import React from 'react';
import { createStackNavigator, createAppContainer } from 'react-navigation';
import TabNavigator from './TabNavigator';
const MainNavigator = createStackNavigator({
Main: TabNavigator },
{
initialRouteName: 'Main',
defaultNavigationOptions: {
headerTitleStyle: {
fontSize: 20,
textTransform: 'uppercase'
}
}
});
export default createAppContainer(MainNavigator);
TabNavigator.js
import React from 'react';
import { Text } from 'react-native';
import { createMaterialTopTabNavigator } from 'react-navigation';
import Ionicons from 'react-native-vector-icons/Ionicons';
import IconBadge from 'react-native-icon-badge';
import ProfileScreen from './screens/ProfileScreen';
import NotificationsScreen from './screens/NotificationsScreen';
import HomeStackNavigator from './HomeStackNavigator';
import CartStackNavigator from './CartStackNavigator';
import QuotesStackNavigator from './QuotesStackNavigator';
import InitialRoute from './InitialRoute';
const TabNavigator = createMaterialTopTabNavigator(
{
Profile: {
screen: props => <ProfileScreen {...props.screenProps} />,
navigationOptions: {
tabBarIcon: ({ tintColor, focused }) => (
<Ionicons
name={focused ? 'ios-person' : 'ios-person'} //TODO change to focused icon
size={30}
style={{ color: tintColor }}
/>
),
}
},
Home: HomeStackNavigator,
Quotes: QuotesStackNavigator,
Notifications: { screen: props => <NotificationsScreen {...props.screenProps} />,
navigationOptions: ({ screenProps }) => ({
tabBarIcon: ({ tintColor, focused }) => (
<IconBadge
MainElement={
<Ionicons
name={focused ? 'ios-notifications' : 'ios-notifications'}
size={30}
style={{ color: tintColor }}
/>
}
BadgeElement={
<Text style={{ color: '#FFFFFF' }}>{screenProps.unreadMessagesCount}</Text>
}
IconBadgeStyle={{ width: 15,
height: 15,
position: 'absolute',
top: 1,
left: -6,
marginLeft: 15,
backgroundColor: 'red' }}
Hidden={screenProps.unreadMessagesCount === 0}
/>
)
})
},
Cart: CartStackNavigator,
},
{ initialRouteName: 'Profile',
tabBarPosition: 'top',
swipeEnabled: false,
animationEnabled: true,
lazy: true,
tabBarOptions: {
showLabel: false,
showIcon: true,
activeTintColor: 'orange',
inactiveTintColor: 'orange',
style: {
backgroundColor: '#555',
},
indicatorStyle: {
color: '#orange'
}
}
}
);
const screenTitles = {
Profile: { title: 'Hola Maestro' },
Home: { title: 'Selecciona la Categoría' },
Quotes: { title: 'Mi Historial de Cotizaciones' },
Notifications: { title: 'Notificaciones' },
Cart: { title: 'Mi Pedido' },
};
TabNavigator.navigationOptions = ({ navigation }) => {
const { routeName } = navigation.state.routes[navigation.state.index];
const headerTitle = screenTitles[routeName].title;
const tabBarVisible = false;
return {
headerTitle,
tabBarVisible
};
};
export default TabNavigator;
Login.js
import React, { Component, Fragment } from 'react';
import { Text, View, StyleSheet, ImageBackground, KeyboardAvoidingView } from 'react-native';
import axios from 'axios';
import Ionicons from 'react-native-vector-icons/Ionicons';
//import Pusher from 'pusher-js/react-native';
import { ENDPOINT, USER_TYPE } from '../config'
import deviceStorage from '../services/deviceStorage';
import { Input, TextLink, Loading, Button } from './common';
import Header from '../components/Header';
class Login extends Component {
constructor(props){
super(props);
this.state = {
username: '',
password: '',
error: '',
loading: false
};
this.pusher = null; // variable for storing the Pusher reference
this.my_channel = null; // variable for storing the channel assigned to this user
this.loginUser = this.loginUser.bind(this);
}
loginUser() {
const { username, password, password_confirmation } = this.state;
axios.post(`${ENDPOINT}/login`, {
user: {
login: username,
password: password
}
})
.then((response) => {
deviceStorage.saveKey("id_token", response.headers.authorization);
this.props.newJWT(response.headers.authorization);
//this.setPusherData();
})
.catch((error) => {
this.onLoginFail();
});
}
onLoginFail() {
this.setState({
error: 'Usuario o contraseña incorrecta',
loading: false
});
}
}
render() {
const { username, password, error, loading } = this.state;
const { container, form, section, errorTextStyle, iconContainer, inputContainer, titleText } = styles;
return (
<View style={container}>
<Header title="¡Bienvenido Amigo Maestro!" />
<View style={form}>
<ImageBackground source={require('./cemento-login.jpg')} style={{ flex: 1, marginBottom: 30 }}>
<View style={{marginTop: 120}}>
<Text style={titleText}>INICIAR SESIÓN</Text>
<View style={section}>
<View style={iconContainer}>
<Ionicons
name={'ios-person'}
size={26}
style={{ color: '#fff', alignSelf: 'center' }}
/>
</View>
<View style={inputContainer}>
<Input
placeholder="Usuario"
value={username}
onChangeText={username => this.setState({ username })}
/>
</View>
</View>
<View style={section}>
<View style={iconContainer}>
<Ionicons
name={'ios-lock'}
size={26}
style={{ color: '#fff', alignSelf: 'center' }}
/>
</View>
<View style={inputContainer}>
<Input
secureTextEntry
placeholder="Contraseña"
value={password}
onChangeText={password => this.setState({ password })}
/>
</View>
</View>
</View>
</ImageBackground>
</View>
<KeyboardAvoidingView
behavior="padding"
keyboardVerticalOffset={30}
>
<TextLink style={{ }} onPress={this.props.formSwitch}>
Aún no estas registrado? Regístrate
</TextLink>
<TextLink style={{ }} onPress={this.props.forgotPassword}>
Olvidaste tu contraseña?
</TextLink>
<Text style={errorTextStyle}>
{error}
</Text>
{!loading ?
<Button onPress={this.loginUser}>
Ingresar
</Button>
:
<Loading size={'large'} />}
</KeyboardAvoidingView>
</View>
);
}
}
const styles = StyleSheet.create({
container: {
flex: 1,
},
form: {
flex: 0.8
},
section: {
flexDirection: 'row',
backgroundColor: '#eee',
borderRadius: 3,
marginTop: 10,
height: 40,
marginLeft: '10%',
marginRight: '10%',
},
titleText: {
color: '#fff',
alignSelf: 'center',
fontSize: 20,
marginBottom: 10
},
errorTextStyle: {
alignSelf: 'center',
fontSize: 18,
color: 'red'
},
iconContainer: {
flex: 0.1,
height: 40,
borderRadius: 3,
alignSelf: 'center',
justifyContent: 'center',
backgroundColor: 'orange',
},
inputContainer: {
flex: 0.8,
alignSelf: 'flex-start',
marginLeft: -70,
}
});
export { Login };

Inside App.js you never change loading to false so the render method never gets to any of the other conditions. Once you have received the token you need to update state and change loading.

Related

please take a look at this code my signup button doesn't direct me to profile component react native

Help me with this so I can carry further on with my work.
Also all the other files which are needed for the solution I can provide you with.
profile.js
import React from "react";
import { StyleSheet, Text, View, StatusBar } from "react-native";
import { render } from "react-dom";
class Profile extends React.Component {
render() {
return (
<View style={styles.container}>
<Text style={styles.textStyle}>This is the profile page </Text>
</View>
);
}
}
const styles = StyleSheet.create({
container: {
backgroundColor: "#455a64",
flex: 1,
alignItems: "center",
justifyContent: "center",
},
textStyle: {
color: "#fff",
fontSize: 18,
},
});
export default Profile;
signup.js
import React from "react";
import {
StyleSheet,
Text,
View,
StatusBar,
TouchableOpacity,
} from "react-native";
import { createNewUser } from "/Users/ayeshasiddiquebutt/elearning9thclassapp/sourcefiles/actions/auth.actions.js";
import { render } from "react-dom";
import { connect } from "react-redux";
import Form from "/Users/ayeshasiddiquebutt/elearning9thclassapp/sourcefiles/components/form.js";
import { compose } from "redux";
import Logo from "/Users/ayeshasiddiquebutt/elearning9thclassapp/sourcefiles/components/logo.js";
import SignupForm from "/Users/ayeshasiddiquebutt/elearning9thclassapp/sourcefiles/components/signupform.js";
import { Actions } from "react-native-router-flux";
import { Field, reduxForm } from "redux-form";
import InputText from "/Users/ayeshasiddiquebutt/elearning9thclassapp/sourcefiles/components/InputText.js";
import Loader from "/Users/ayeshasiddiquebutt/elearning9thclassapp/sourcefiles/components/Loader.js";
class Signup extends React.Component {
goBack() {
Actions.pop();
}
createNewUser = (values) => {
this.props.dispatch(createNewUser(values));
};
onSubmit = (values) => {
this.createNewUser(values);
};
renderTextInput = (field) => {
const {
meta: { touched, error },
label,
secureTextEntry,
maxLength,
keyboardType,
placeholder,
input: { onChange, ...restInput },
} = field;
return (
<View>
<InputText
onChangeText={onChange}
maxLength={maxLength}
placeholder={placeholder}
keyboardType={keyboardType}
secureTextEntry={secureTextEntry}
label={label}
{...restInput}
/>
{touched && error && <Text style={styles.errorText}>{error}</Text>}
</View>
);
};
render() {
const { createUsers, handleSubmit } = this.props;
return (
<View style={styles.container}>
{createUsers.isLoading && <Loader />}
<Logo />
<Field
name="name"
placeholder=" First Name"
component={this.renderTextInput}
/>
<Field
name="name"
placeholder=" Last Name"
component={this.renderTextInput}
/>
<Field
name="email"
placeholder="Email"
component={this.renderTextInput}
/>
<Field
name="password"
placeholder="Password"
secureTextEntry={true}
component={this.renderTextInput}
/>
<TouchableOpacity
style={styles.button}
onPress={handleSubmit(this.onSubmit)}
>
<Text style={styles.buttonText}>Signup</Text>
</TouchableOpacity>
<View style={styles.signupTextCont}>
<Text style={styles.signupText}>Already have an account?</Text>
<TouchableOpacity onPress={this.goBack}>
<Text style={styles.signupButton}> Sign in</Text>
</TouchableOpacity>
</View>
</View>
);
}
}
const validate = (values) => {
const errors = {};
if (!values.name) {
errors.name = "First Name is required";
}
if (!values.name) {
errors.name = "Last Name is required";
}
if (!values.email) {
errors.email = "Email is required";
}
if (!values.password) {
errors.password = "Password is required";
}
return errors;
};
const styles = StyleSheet.create({
container: {
backgroundColor: "#455a64",
flex: 1,
alignItems: "center",
justifyContent: "center",
},
signupTextCont: {
flexGrow: 1,
alignItems: "flex-end",
justifyContent: "center",
paddingVertical: 16,
flexDirection: "row",
},
signupText: {
color: "rgba(255,255,255,0.6)",
fontSize: 16,
},
signupButton: {
color: "#ffffff",
fontSize: 16,
fontWeight: "500",
},
button: {
width: 300,
backgroundColor: "#1c313a",
borderRadius: 25,
marginVertical: 10,
paddingVertical: 13,
},
buttonText: {
fontSize: 16,
fontWeight: "500",
color: "#ffffff",
textAlign: "center",
},
errorText: {
color: "#ffffff",
fontSize: 14,
paddingHorizontal: 16,
paddingBottom: 8,
},
inputBox: {
width: 300,
backgroundColor: "rgba(255, 255,255,0.2)",
borderRadius: 25,
paddingHorizontal: 16,
fontSize: 16,
color: "#ffffff",
marginVertical: 10,
},
});
mapStateToProps = (state) => ({
createUsers: state.authReducer.createUsers,
});
mapDispatchToProps = (dispatch) => ({
dispatch,
});
export default compose(
connect(mapStateToProps, mapDispatchToProps),
reduxForm({
form: "register",
validate,
})
)(Signup);
auth.reducer.js
import { combineReducers } from "redux";
const createUsers = (state = {}, action) => {
switch (action.type) {
case "CREATE_USER_LOADING":
return {
isLoading: true,
isError: false,
isSuccess: false,
errors: null,
isLoggedIn: false,
};
case "CREAT_USER_SUCCESS":
return {
isLoading: false,
isError: false,
isSuccess: true,
errors: null,
isLoggedIn: true,
};
case "CREAT_USER_FAIL":
return {
isLoading: false,
isError: true,
isSuccess: false,
errors: action.payload,
isLoggedIn: false,
};
default:
return state;
}
};
/*const authData = (state = {}, action) => {
switch (action.type) {
case "AUTH_USER_SUCCESS":
return {
token: action.token,
isLoggedIn: true,
};
case "AUTH_USER_FAIL":
return {
token: null,
isLoggedIn: false,
};
default:
return state;
}
};
const loginUser = (state = {}, action) => {
switch (action.type) {
case "LOGIN_USER_LOADING":
return {
isLoading: true,
isError: false,
isSuccess: false,
errors: null,
};
case "LOGIN_USER_SUCCESS":
return {
isLoading: false,
isError: false,
isSuccess: true,
errors: null,
};
case "LOGIN_USER_FAIL":
return {
isLoading: false,
isError: true,
isSuccess: false,
errors: action.payload,
};
default:
return state;
}
};*/
export default combineReducers({
createUsers,
//loginUser,
//authData,
});
routes.js
import React, { Component } from "react";
import {
StyleSheet,
Text,
View,
StatusBar,
TouchableOpacity,
} from "react-native";
import { Router, Stack, Scene } from "react-native-router-flux";
import Login from "../pages/login.js";
import Signup from "/Users/ayeshasiddiquebutt/elearning9thclassapp/sourcefiles/pages/signup.js";
import Profile from "../pages/profile.js";
class Routes extends React.Component {
render() {
return (
<Router>
<Scene>
<Scene key="root" hideNavBar={true} initial={!this.props.isLoggedIn}>
<Scene key="signup" component={Signup} title="Register" />
<Scene key="login" component={Login} />
</Scene>
<Scene key="app" hideNavBar={true} initial={this.props.isLoggedIn}>
<Scene key="profile" component={Profile} initial={true} />
</Scene>
</Scene>
</Router>
);
}
}
export default Routes;
Main.js
import React from "react";
import {
StyleSheet,
Text,
View,
StatusBar,
TouchableOpacity,
} from "react-native";
import { render } from "react-dom";
import { createUsers } from "/Users/ayeshasiddiquebutt/elearning9thclassapp/sourcefiles/reducers/auth.reducer.js";
import { connect } from "react-redux";
import Routes from "/Users/ayeshasiddiquebutt/elearning9thclassapp/sourcefiles/components/routes.js";
import { Actions } from "react-native-router-flux";
class Main extends React.Component {
render() {
const { createUsers } = this.props;
console.log(this.props.createUsers.isLoggedIn);
return (
<View style={styles.container}>
<StatusBar backgroundColor="#1c313a" barStyle="light-content" />
<Routes isLoggedIn={this.props.createUsers.isLoggedIn} />
</View>
);
}
}
const styles = StyleSheet.create({
container: {
flex: 1,
},
});
mapStateToProps = (state) => ({
createUsers: state.authReducer.createUsers,
});`enter code here`
export default connect(mapStateToProps, null)(Main);

Error in Navigating Screen using Button props in React Native

I've been trying some codes for the navigation in react native, I want to navigate from Listlab screen to FormScreen for updating which mean I want to navigate the screen and pass the value to new screen and its textfield. But when I tried, it shown me an error that I already tried to solve it for many times. Can you help me to solve this error, thank you :D
Here's The Error Message:
And Here's my Listlab Code:
import React, { Component } from 'react';
import { View, Text, StyleSheet, Platform, StatusBar} from 'react-native';
import PropTypes from 'prop-types';
import { Card, CardTitle, CardContent, CardAction, CardButton, CardImage } from 'react-native-material-cards'
import { CardItem } from 'native-base';
import { ScrollView } from 'react-native-gesture-handler';
import { createAppContainer } from 'react-navigation';
import {createStackNavigator } from 'react-navigation-stack';
import Button from 'react-native-button';
import { withNavigation } from 'react-navigation';
class ListLab extends Component {
_OnButtonPress(no_pengajuan) {
Alert.alert(no_pengajuan.toString());
}
handleDelete(id){
let url = "http://URL:8000/api/pinjams/"+id ;
// let data = this.state;
fetch(url,{
method:'DELETE',
headers:{
"Content-Type" : "application/json",
"Accept" : "application/json"
},
})
.then((result) => {
result.json().then((resp) => {
console.warn("resp", resp)
alert("Data is Removed")
})
})
}
render() {
this._OnButtonPress = this._OnButtonPress.bind(this);
return (
<View style={styles.pinjamList}>
<StatusBar hidden />
{this.props.pinjams.map((pinjam) => {
return (
<View key={pinjam.id}>
{/* Baru nambah data */}
<Card>
<CardImage
source={{uri: 'http://www.rset.edu.in/pages/uploads/images/computerLab-img1.jpg'}}
title={pinjam.lab }
/>
<CardTitle
title={ pinjam.ketua_kegiatan }
subtitle={ pinjam.keperluan }
/>
<CardContent><Text>{ pinjam.tanggal_mulai} - {pinjam.tanggal_selesai }</Text></CardContent>
<CardContent><Text>{ pinjam.jam_mulai } - {pinjam.jam_selesai }</Text></CardContent>
</Card>
<Button
style={{fontSize:20, color:'red'}}
styleDisabled={{color:'grey'}}
onPress ={()=>{this.handleDelete(pinjam.id)}}
> {"\n"} Delete
</Button>
<Button
style={{fontSize:20, color:'green'}}
styleDisabled={{color:'grey'}}
onPress ={()=>{this.props.navigation.navigate('FormScreen')}}
> {"\n"} Update
</Button>
</View>
)
})}
</View>
);
}
}
const styles = StyleSheet.create({
pinjamList: {
flex: 1,
flexDirection: 'column',
justifyContent: 'space-around',
},
pinjamtext: {
fontSize: 14,
fontWeight: 'bold',
textAlign: 'center',
}
});
export default withNavigation(ListLab);
And This one is my FormScreen Code:
import React , { Component } from 'react';
import {
ScrollView,
View,
Text,
StyleSheet,
StatusBar
} from 'react-native';
import { Header, Left, Right, Icon, Footer, Label} from 'native-base';
import Button from 'react-native-button';
import t from 'tcomb-form-native';
import { Dropdown } from 'react-native-material-dropdown';
import { TextField } from 'react-native-material-textfield';
import DatePicker from 'react-native-datepicker';
import moment from 'moment';
class FormScreens extends Component {
static navigationOptions = {
drawerIcon : ({tintColor})=>(
<Icon name="paper" style={{ fontSize: 24, color: tintColor }}/>
)
}
constructor(){
super();
this.state = {
ketua_kegiatan: '',
lab: '',
level: '',
tanggal_mulai: '',
tanggal_selesai: '',
jam_mulai: '',
jam_selesai: '',
daftar_nama: '',
keperluan: '',
kontak_ketua:'',
dosen_pembina: '',
app_laboran: '',
app_kalab: '',
app_kajur: '',
app_pudir: '',
}
}
submit(id){
let url = "http://URL:8000/api/pinjams"+id;
let data = this.state;
fetch(url,{
method:'PUT',
headers:{
"Content-Type" : "application/json",
"Accept" : "application/json"
},
body: JSON.stringify(data)
})
.then((result) => {
result.json().then((resp) => {
console.warn("resp", resp)
alert("Data is Updated")
})
})
}
render() {
let lab = [{
value: '313',
}, {
value: '316',
}, {
value: '317',
}, {
value: '318',
}, {
value: '319',
}, {
value: '320',
}, {
value: '324',
}, {
value: '325',
}, {
value: '329',
}, {
value: '330',
}, {
value: '234',
}, {
value: '283',
}, {
value: '218',
}, {
value: '224',
}, {
value: '225',
}, {
value: '230',
}, {
value: '233',
}, {
value: '135',
}, {
value: '136',
}, {
value: '137',
}, {
value: 'Workshop',
}, {
value: 'Lab Bahasa',
}];
let level = [{
value: 1,
}, {
value: 2,
}, {
value: 3,
}];
return (
//08-08-2019 (Ubah view menjadi ScrollView)
<ScrollView style={styles.container}>
<StatusBar hidden />
<Header style={{backgroundColor:'orange', flex:0.8}}>
<Left style={{justifyContent:"flex-start",flex:1,marginTop:5}}>
<Icon name="menu" onPress={()=>this.props.navigation.openDrawer()} />
</Left>
</Header>
<View style={{padding:20}}>
<Text style={{fontSize:20,textAlign: 'center',paddingLeft:20,fontWeight: 'bold'}}>{"\n"}Halaman Pengajuan</Text>
<TextField
label = 'ketua_kegiatan'
// value = {ketua_kegiatan}
onChangeText={ (ketua_kegiatan) => this.setState({ ketua_kegiatan }) }
// onChange={(data) => { this.setState({ketua_kegiatan:data.target.value}) }}
value = {this.state.ketua_kegiatan}
/>
<Dropdown
label='Laboratorium'
data={lab}
onChangeText={ (lab) => this.setState({ lab }) }
/>
<Dropdown
label='Level'
data={level}
onChangeText={ (level) => this.setState({ level }) }
/>
<TextField
label = 'Tanggal Mulai'
// value = {tanggal_mulai}
onChangeText={ (tanggal_mulai) => this.setState({ tanggal_mulai }) }
// onChange={(data) => { this.setState({tanggal_mulai:data.target.value}) }}
value = {this.state.tanggal_mulai}
/>
<TextField
label = 'Tanggal Selesai'
// value = {tanggal_selesai}
onChangeText={ (tanggal_selesai) => this.setState({ tanggal_selesai }) }
// onChange={(data) => { this.setState({tanggal_selesai:data.target.value}) }}
value = {this.state.tanggal_selesai}
/>
<TextField
label = 'Jam Mulai'
// value = {jam_mulai}
onChangeText={ (jam_mulai) => this.setState({ jam_mulai }) }
// onChange={(data) => { this.setState({jam_mulai:data.target.value}) }}
value = {this.state.jam_mulai}
/>
<TextField
label = 'Jam Selesai'
// value = {jam_selesai}
onChangeText={ (jam_selesai) => this.setState({ jam_selesai }) }
// onChange={(data) => { this.setState({jam_selesai:data.target.value}) }}
value = {this.state.jam_selesai}
/>
<TextField
label = 'Keperluan'
// value = {keperluan}
onChangeText={ (keperluan) => this.setState({ keperluan }) }
// onChange={(data) => { this.setState({keperluan:data.target.value}) }}
value = {this.state.keperluan}
/>
<TextField
label = 'Daftar Nama'
// value = {daftar_nama}
onChangeText={ (daftar_nama) => this.setState({ daftar_nama }) }
// onChange={(data) => { this.setState({daftar_nama:data.target.value}) }}
value = {this.state.daftar_nama}
/>
<TextField
label = 'kontak_ketua'
// value = {kontak_ketua}
onChangeText={ (kontak_ketua) => this.setState({ kontak_ketua }) }
// onChange={(data) => { this.setState({kontak_ketua:data.target.value}) }}
value = {this.state.kontak_ketua}
/>
<TextField
label = 'Dosen Pembina'
// value = {dosen_pembina}
onChangeText={ (dosen_pembina) => this.setState({ dosen_pembina }) }
// onChange={(data) => { this.setState({dosen_pembina:data.target.value}) }}
value = {this.state.dosen_pembina}
/>
<TextField
label = 'app_laboran'
// value = {app_laboran}
onChangeText={ (app_laboran) => this.setState({ app_laboran }) }
// onChange={(data) => { this.setState({app_laboran:data.target.value}) }}
value = {this.state.app_laboran}
/>
<Button
style={{fontSize:20, color:'orange'}}
styleDisabled={{color:'grey'}}
onPress ={()=>{this.submit(pinjam.id)}}
> {"\n"} Submit
</Button>
</View>
{/* <Form type={Pengajuan}/> */}
<Footer style={{backgroundColor:'white'}}>
<Text style={{paddingTop:10,color:'grey'}}>{"\n"}Copyright reserved to #Leony_vw</Text>
</Footer>
</ScrollView>
);
}
}
export default FormScreens;
const styles = StyleSheet.create({
container: {
flex: 1,
backgroundColor: '#fff',
// ...Platform.select({
// android: {
// marginTop: StatusBar.currentHeight
// }
// })
},
});
Here's my App.js:
import React from 'react';
import { StyleSheet, Text, View, SafeAreaView,ScrollView, Dimensions, Image } from 'react-native';
import { createDrawerNavigator, DrawerItems, createAppContainer } from 'react-navigation';
// import HomeScreen from './screens/HomeScreen';
// import FormScreen from './screens/FormScreen';
// import SigninScreen from './screens/SigninScreen';
import HomeScreen from './screens/laboran/HomeScreen';
import FormScreen from './screens/laboran/FormScreen';
import * as firebase from "firebase";
const { width } = Dimensions.get('window');
var firebaseConfig = {
apiKey: "XXXXXX",
authDomain: "XXXXX",
databaseURL: "XXXXX",
projectId: "XXXXX",
storageBucket: "XXXXX",
messagingSenderId: "XXXXX",
appId: "XXXXX"
};
// Initialize Firebase
firebase.initializeApp(firebaseConfig);
export default class App extends React.Component{
render() {
return (
<Apps/>
);
}
}
const CustomDrawerComponent = (props) => (
<SafeAreaView style={{ flex:1 }}>
<View style={{height:150, backgroundColor: 'white', alignItems :'center', justifyContent:'center'}}>
<Image source={require('./assets/up2.png')} style={{height:50, width:50,borderRadius:35 }}/>
</View>
<ScrollView>
<DrawerItems {...props}/>
</ScrollView>
</SafeAreaView>
)
const AppDrawerNavigator = createDrawerNavigator({
// Login:SigninScreen,
Home:HomeScreen,
Form:FormScreen
}, {
contentComponent: CustomDrawerComponent,
drawerWidth: width,
contentOptions:{
activeTintColor:'orange'
}
})
const Apps = createAppContainer(AppDrawerNavigator)
const styles = StyleSheet.create({
container: {
flex: 1,
backgroundColor: '#fff',
alignItems: 'center',
justifyContent: 'center',
},
});
That is probably because Listlab is rendered by a component that is actually a screen.
For example, let say your FormScreen would render the Listlab component. FormScreen has access to the navigation prop, but Listlab does not.
You have 2 solutions:
- pass the navigation prop to Listlab
- use the withNavigation HOC
I found the solution last night, I think I can's just navigate from ListLab because ListLab is just like a child screen of HomeScreen. When I try it on HomeScreen, the prop is doing fine, and it can navigate to my FormScreen tho. And also, I think I did call the wrong alias of FormScreen in App.js and that's the problem as well. But now, I would like to put the button and the navigation in ListLab, I still wonder how can I navigate using button in child screen. But thanks guys for helping me :D Cheers!

The component for route '' must be a React Component

I'm new to react-native and am trying to use the Redux framework, I've encountered this problem: (The component for route ' ' must be a React component):
Thank you in advance.
Screen Error
Index.js
import React from 'react'
import { Provider } from 'react-redux'
import { AppRegistry } from 'react-native';
import { name as appName } from './app.json';
import Menu from './app/componnts/Menu'
import storeConfig from './app/store/storeConfig'
const store = storeConfig()
const Redux = () => {
return (
<Provider store={store}>
<Menu />
</Provider>
)
}
AppRegistry.registerComponent(appName, () => Redux);
Menu.js
import React, { Component } from 'react'
import {
StyleSheet,
SafeAreaView,
ScrollView,
Dimensions,
View,
Image,
Text
} from 'react-native'
import { createDrawerNavigator, DrawerItems, } from 'react-navigation'
import Login from './Login/Login'
import Viatura from './Viatura/Viatura'
export default class App extends Component {
render() {
return (
<AppDrawerNavigator />
)
}
}
const CustomDrawerComponent = (props) => (
<SafeAreaView style={{ flex: 1 }}>
<ScrollView>
<DrawerItems {...props} />
</ScrollView>
</SafeAreaView>
)
const AppDrawerNavigator = createDrawerNavigator({
Login,
Viatura,
}, {
contentComponent: CustomDrawerComponent,
drawerWidth: 300,
contentOptions: {
activeTintColor: 'orange'
}
})
Login.js
import React, { Component } from 'react'
import { connect } from 'react-redux'
import { loginStore } from '../../store/actions/user.js';
import { Text, View, ImageBackground, Dimensions, Image, TextInput, TouchableOpacity, Alert } from 'react-native'
import Icon from 'react-native-vector-icons/FontAwesome'
import axios from 'axios'
import { createIconSetFromIcoMoon } from 'react-native-vector-icons'
import { API_MOTORISTAS_LOGIN } from '../../config'
import icoMoonConfig from '../../resources/fonts/selection.json'
import styles from './styles'
import bgImage from '../../images/fundo-vertical-preto.jpg'
import logo from '../../images/logo-tg-v-01.png'
const MyIcon = createIconSetFromIcoMoon(icoMoonConfig, 'icomoon', 'icomoon.ttf');
class Login extends Component {
constructor(props) {
super(props)
this.state = {
user: '',
password: '',
}
this.loginUser = this.loginUser.bind(this)
}
loginUser = () => {
try {
const { user, password } = this.state
this.setState({ error: '', })
axios.post(`${API_MOTORISTAS_LOGIN}`,
{
'param1': this.state.user,
'param2': this.state.password
}, {
"headers": {
'Content-Type': 'application/json',
}
}).then((response) => {
if (response.data.error) {
Alert.alert((response.data.error));
} else {
this.props.onLogin({ ...this.state })
const api_token = response.data.api_token
this.props.navigation.navigate('Viatura', {
api_token: api_token,
})
}
})
.catch((error) => {
console.log("axios error:", error);
});
} catch (err) {
Alert.alert((err))
}
}
static navigationOptions = {
drawerIcon: ({ tintColor }) => (
<MyIcon name="fonte-tg-33" style={{ fontSize: 24, color: tintColor }} />
)
}
render() {
return (
<ImageBackground
source={bgImage}
style={styles.backgroundContainer}>
<View
style={{
height: (Dimensions.get('window').height / 10) * 10,
alignItems: 'center',
justifyContent: 'center',
}}>
<View style={styles.logoContainer}>
<Image source={logo} style={styles.logo} />
</View>
<View style={styles.inputText}>
<View style={styles.iconContainer}>
<MyIcon style={styles.icon} name="fonte-tg-39" size={25} />
</View>
<TextInput
style={styles.input}
placeholder={'User'}
placeholderTextColor={'rgba(0, 0, 0, 0.6)'}
underlineColorAndroid='transparent'
value={this.state.user}
onChangeText={user => this.setState({ user })}
/>
</View>
<View style={styles.inputText}>
<View style={styles.iconContainer}>
<MyIcon style={styles.icon} name="fonte-tg-73" size={25} />
</View>
<TextInput
style={styles.input}
placeholder={'Password'}
secureTextEntry={true}
placeholderTextColor={'rgba(0, 0, 0, 0.6)'}
underlineColorAndroid='transparent'
value={this.state.password}
onChangeText={password => this.setState({ password })}
/>
</View>
<View style={styles.buttonsLogin}>
<TouchableOpacity style={styles.btnSair}>
<Text style={styles.text}> Sair </Text>
</TouchableOpacity>
<TouchableOpacity onPress={this.loginUser} style={styles.btnEntrar}>
<Text style={styles.text}> Entrar </Text>
</TouchableOpacity>
</View>
</View>
</ImageBackground>
)
}
}
const mapDispatchToProps = dispatch => {
return {
onLogin: user => dispatch(loginStore(user))
}
}
export default connect(null, mapDispatchToProps)(Login);
actionTypes.js
export const USER_LOGGED_IN = 'USER_LOGGED_IN';
export const USER_LOGGED_OUT = 'USER_LOGGED_OUT';
user.js (inside actions folder)
import { USER_LOGGED_IN, USER_LOGGED_OUT } from './actionTypes'
export const login = user => {
return {
type: USER_LOGGED_IN,
payload: user
}
}
export const logout = () => {
return {
type: USER_LOGGED_OUT,
}
}
user.js (inside reducers folder)
import { USER_LOGGED_IN, USER_LOGGED_OUT } from '../actions/actionTypes'
const initalState = {
user: null,
password: null
}
const reducer = (state = initalState, action) => {
switch (action.type) {
case USER_LOGGED_IN:
return {
...state,
user: action.paypload.user,
password: action.paypload.password
}
case USER_LOGGED_OUT:
return {
...state,
user: null,
password: null,
}
default:
return state
}
}
export default reducer
storeConfig.js
import { createStore, combineReducers } from 'redux'
import userReducer from './reducers/user'
const reducers = combineReducers({
user: userReducer,
})
const storeConfig = () => {
return createStore(reducers)
}
export default storeConfig
As I said at the beginning of the post, I'm still a beginner at react-native, so I'm posting several snippets of code so that I can be as clear as possible about how my situation is.
I don't think your screen is properly setting export default.
can you change this code?
import React, { Component } from 'react'
import {
StyleSheet,
SafeAreaView,
ScrollView,
Dimensions,
View,
Image,
Text
} from 'react-native'
import { createDrawerNavigator, DrawerItems, } from 'react-navigation'
import Login from './Login/Login'
import Viatura from './Viatura/Viatura'
export default class App extends Component {
render() {
return (
<AppDrawerNavigator />
)
}
}
const CustomDrawerComponent = (props) => (
<SafeAreaView style={{ flex: 1 }}>
<ScrollView>
<DrawerItems {...props} />
</ScrollView>
</SafeAreaView>
)
const AppDrawerNavigator = createDrawerNavigator(
{
Login : () => <Login />,
Viatura : () => <Viatura />
},
{
contentComponent: CustomDrawerComponent,
drawerWidth: 300,
contentOptions: {
activeTintColor: 'orange'
}
}
)
OR
import { Login } from './Login/Login'
import { Viatura } from './Viatura/Viatura'
...
const AppDrawerNavigator = createDrawerNavigator(
{
Login : { screen: Login },
Viatura : { screen: Viatura }
},
{
contentComponent: CustomDrawerComponent,
drawerWidth: 300,
contentOptions: {
activeTintColor: 'orange'
}
}
)
Try this
const AppDrawerNavigator = createDrawerNavigator({
Login:Login,
Viatura:Login,
}, {
contentComponent: CustomDrawerComponent,
drawerWidth: 300,
contentOptions: {
activeTintColor: 'orange'
}
})

AsyncStorage returns null [react-native]

I have a createSwitchNavigator which has 3 routes with initialRouteName as AuthLoading
App.js
import AuthLoadingScreen from './screens/AuthLoadingScreen';
import {
createDrawerNavigator,
createBottomTabNavigator,
DrawerItems,
createSwitchNavigator,
createStackNavigator
} from "react-navigation";
import AuthScreen from "./screens/AuthScreen";
import ProductsScreen from "./screens/ProductsScreen";
import AuthLoadingScreen from "./screens/AuthLoadingScreen";
import ForgetPasswordScreen from "./screens/ForgetPasswordScreen";
import ProductsDemo from "./screens/ProductsDemo";
import RegisterScreen from "./screens/RegisterScreen";
const AppNavigator = () => {
return <MainNavigation />;
};
const AppBottomTabNavigator = createBottomTabNavigator(
{
home: ProductsScreen
}
);
const MainNavigation = createDrawerNavigator(
{
Home: AppBottomTabNavigator,
},
{
drawerWidth: width - width / 4,
drawerPosition: "left",
drawerOpenRoute: "DrawerOpen",
drawerCloseRoute: "DrawerClose",
drawerToggleRoute: "DrawerToggle",
drawerBackgroundColor: "#fff",
initialRouteName: "Home"
}
);
const AuthDrawerNavigator = createDrawerNavigator(
{
Products: createStackNavigator(
{
SignIn: AuthScreen,
ForgetPwd: ForgetPasswordScreen,
SignUp: RegisterScreen,
Product: ProductsDemo
},
{
initialRouteName: "Product",
navigationOptions: {
header: null
}
}
)
},
{
drawerWidth: width - width / 4,
drawerPosition: "left"
}
);
class App extends Component {
componentDidMount() {
SplashScreen.hide();
navigatorRef = this.navigator;
}
render() {
const Main = createSwitchNavigator({
AuthLoading: AuthLoadingScreen,
Auth: AuthDrawerNavigator,
App: AppNavigator
});
return (
<StoreProvider store={store}>
<PaperProvider theme={theme}>
<Main />
</PaperProvider>
</StoreProvider>
);
}
}
export default App;
The AuthLoadingScreen just checks... if app has a token, log user in else route to AuthDrawerNavigator, the AuthDrawerNavigator has a registration and login page.
AuthLoadingScreen.js
import React, { Component } from "react";
import { View, ActivityIndicator, AsyncStorage, StatusBar } from
"react-native";
class AuthLoadingScreen extends Component {
constructor() {
super()
this.loadApp()
}
loadApp = async () => {
const userToken = await AsyncStorage.getItem('userToken');
this.props.navigation.navigate(userToken? 'App' : 'Auth');
}
render() {
return (
<View
style={{
justifyContent: "center",
alignItems: "center",
flex: 1,
backgroundColor: "#fff"
}}
>
<StatusBar translucent={false} backgroundColor="#007aff" />
<ActivityIndicator size="large" color="#007aff" />
</View>
);
}
}
export default AuthLoadingScreen;
In my RegisterScreen, as the user gets registered on backend, im storing his or her details locally using AsyncStorage...
const registerUser = async (first_name, last_name, email, pwd_1, phone, dispatch) => {
axios.post(`${ROOT_URL}registerUser`, {
phone: `+91${phone}`,
first_name: `${first_name}`,
last_name: `${last_name}`,
email: `${email}`,
pwd: `${pwd_1}`
})
.catch(err => dispatch({
type: REQ_FAIL,
val: err.message
}))
dispatch({
type: REQ_SUCCESS
})
await AsyncStorage.setItem('f_name', first_name);
await AsyncStorage.setItem('l_name', last_name);
await AsyncStorage.setItem('email', email);
await AsyncStorage.setItem('phone', phone);
}
Now, as the user is getting registered, im storing their details locally and after registration im routed to loginScreen and after login, im able to see details in homeScreen
ProductsScreen.js
import React, { Component } from "react";
import {
View,
Text,
StyleSheet,
StatusBar,
Image,
TextInput,
AsyncStorage,
} from "react-native";
import { Appbar } from "react-native-paper";
import { Icon } from "react-native-elements";
class ProductsScreen extends Component {
state = {
first_name: "",
last_name: "",
phone: "",
email: ""
};
async componentWillMount() {
let f_name = await AsyncStorage.getItem("f_name");
let l_name = await AsyncStorage.getItem("l_name");
let phone = await AsyncStorage.getItem("phone");
let email = await AsyncStorage.getItem("email");
this.setState({
first_name: f_name,
last_name: l_name,
phone: phone,
email: email
});
}
render() {
const { navigation } = this.props;
return (
<View style={{ flex: 1, backgroundColor: "#fff" }}>
<View style={{ flex: 1 }}>
<View
style={{
backgroundColor: "#fff",
borderRadius: 12,
flexDirection: "row",
justifyContent: "space-around",
alignItems: "center",
marginHorizontal: 12,
marginVertical: 5,
elevation: 1,
zIndex: 9
}}
>
<Image
style={{
height: 50,
width: 50,
marginVertical: 8
}}
alignSelf="center"
resizeMode="contain"
source={require("../components/Images/avatar.png")}
/>
<View style={{ justifyContent: "space-around" }}>
<Text>{`${this.state.first_name} ${
this.state.last_name
}`}</Text>
<Text>{this.state.phone}</Text>
<Text>{this.state.email}</Text>
</View>
</View>
</View>
</View>
);
}
}
export default ProductsScreen;
But next time as the user is already registered,user is directly routed to loginScreen and after logging in, this time AsyncStorage is returning null
Though the code for retrieving values from asyncStorage is same as above:
async componentWillMount() {
let f_name = await AsyncStorage.getItem("f_name");
let l_name = await AsyncStorage.getItem("l_name");
let phone = await AsyncStorage.getItem("phone");
let email = await AsyncStorage.getItem("email");
this.setState({
first_name: f_name,
last_name: l_name,
phone: phone,
email: email
});
}

how can I navigate from LoginForm.js to product.js after successfull login

how to navigate from LoginForm.js to product.js ?
route.js
import React from 'react';
import { StyleSheet,View,Text } from 'react-native';
import { StackNavigator } from 'react-navigation';
import Home from './pages/home';
import Products from './pages/product';
// import Products from './pages/components/LoginForm';
const navigation = StackNavigator({
Home : { screen: Home },
// Login : { screen: LoginForm },
Products : { screen: Products },
});
export default navigation;
home.js
import React from 'react';
import { StyleSheet, Text, View, Button, StatusBar, Image } from 'react-native';
import LoginForm from './components/LoginForm';
export default class Home extends React.Component {
static navigationOptions = {
header: null
};
render() {
return (
<View style = { styles.container }>
<StatusBar
backgroundColor="#007ac1" barStyle="light-content"/>
<View style= { styles.logoContainer }>
<Image style = {styles.logo} source={require('../images/logo.png')} />
</View>
<View style= { styles.formContainer }>
<LoginForm />
</View>
</View>
);
}
}
const styles = StyleSheet.create({
container: {
flex: 1,
backgroundColor: '#03a9f4'
},
logoContainer: {
flexGrow: 1, justifyContent:'center', alignItems:'center'
},
logo: {
width: 80, height: 80
},
formContainer: {
}
});
LoginForm.js
import React from 'react';
import { StyleSheet, Text, View ,TextInput, TouchableOpacity } from 'react-native';
export default class LoginForm extends React.Component {
constructor(props){
super(props)
this.state={
userName:'',
password:'',
type:'A'
}
}
userLogin = () =>{
const { userName } = this.state;
const { password } = this.state;
const { type } = this.state;
fetch('http://192.168.0.4:3000/notes',{
method: 'POST',
headers: {
Accept: 'application/json',
'Content-Type': 'application/json',
},
body:JSON.stringify({
userName : userName,
password : password,
type : type
})
})
.then((response)=> response.json())
.then((responseJson) => {
if(responseJson.response.success == true) {
// alert(responseJson.response.result);
navigate('Products');
}else{
alert(responseJson.response.result);
}
})
.catch((error)=>{
console.error(error);
})
}
render() {
return (
<View style = {styles.container}>
<TextInput
underlineColorAndroid="transparent"
placeholder="Username or Email"
placeholderTextColor = "rgba(255,255,255,0.7)"
returnKeyType="next"
onSubmitEditing={() => this.passwordInput.focus()}
onChangeText = {userName => this.setState({userName})}
style={styles.input} />
<TextInput
placeholder="Password"
underlineColorAndroid="transparent"
secureTextEntry
returnKeyType="go"
placeholderTextColor = "rgba(255,255,255,0.7)"
ref = {(input) => this.passwordInput = input}
onChangeText = {password => this.setState({password})}
style={styles.input} />
<TouchableOpacity style={styles.buttonContainer} onPress={this.userLogin} >
<Text style={styles.buttonText}>LOGIN</Text>
</TouchableOpacity>
</View>
)
}
}
const styles = StyleSheet.create({
container : {
padding:20
},
input: {
height:40, backgroundColor: 'rgba(255,255,255,0.2)', marginBottom:20,
color:'#FFF', paddingHorizontal:10, borderRadius:5
},
buttonContainer: {
backgroundColor: "#2980b9", paddingVertical:10, borderRadius:5
},
buttonText: {
textAlign :'center', color:'#FFFFFF', fontWeight:'700'
}
});
product.js
import React from 'react';
import { StyleSheet, Text, View, Button } from 'react-native';
export default class Product extends React.Component {
static navigationOptions = {
// title: 'Home',
header: null
};
render() {
return (
<View style = { styles.container }>
<Text> Product Page open </Text>
<Button
title="Go to Home"
onPress={() => this.props.navigation.navigate('Home')}
/>
</View>
);
}
}
const styles = StyleSheet.create({
container: {
flex: 1,
backgroundColor: '#fff',
alignItems: 'center',
justifyContent: 'center',
},
});
Make LoginForm as part of navigator (it is currently commented). Then inside the userLogin function use this.props.navigation.navigate('Products') to navigate, take a look at the navigation doc
userLogin = () =>{
...
fetch('http://192.168.0.4:3000/notes',{
...
})
.then((response)=> response.json())
.then((responseJson) => {
if(responseJson.response.success == true) {
// alert(responseJson.response.result);
this.props.navigation.navigate('Products');
}else{
alert(responseJson.response.result);
}
})
.catch((error)=>{
console.error(error);
})
}
Hope this will help!