How to get value from login and show at home - react-native

I want to show username and role at home.js
Im following a tutor but got error undefined is not an object (evaluating '_this.props.navigation.navigate') ..
Maybe someone can help me..
This is Form.js
import React, { Component } from 'react';
import { Text, View, StyleSheet, TextInput, TouchableOpacity, AsyncStorage} from 'react-native';
import { Actions } from 'react-native-router-flux';
const ACCESS_TOKEN = 'access_token';
export default class Form extends Component {
constructor(props){
super(props);
this.state ={
grant_type : "password",
scope : "",
client_id : "",
client_secret : "",
username : "",
password : "",
error : "",
accessTokennya : "",
};
}
async storeToken(accessToken){
try{
await AsyncStorage.setItem(ACCESS_TOKEN, accessToken);
this.getToken();
}catch (error){
console.log("something where wrong")
}
}
async getToken(){
try{
let token = await AsyncStorage.getItem(ACCESS_TOKEN);
console.log("token is : "+ token)
}catch (error){
console.log("something where wrong")
}
}
async removeToken(){
try {
let token = await AsyncStorage.removeItem(ACCESS_TOKEN);
this.getToken();
} catch(error){
console.log("Something went wrong")
}
}
async onLoginPressed(){
try {
let response = await fetch('https://bpm.asihputera.or.id/asihputera/oauth2/token', {
method: 'POST',
headers: {
'Content-Type' : 'application/json',
'Accept-Encoding' : 'gzip, deflate',
'Authorization' : 'Bearer cde4e4bc600afcb604fb2ba078c60a16e29dac04',
'User-Agent' : 'PostmanRuntime/7.15.2',
'Accept' : '*/*',
'Cache-Control' : 'no-cache',
'Postman-Token' : 'ad9e715b-a2af-4f3f-86dd-11a7b6ec6037,f00ce420-e144-47ec-be83-756ec1fbc5d2',
'Host' : 'bpm.asihputera.or.id',
'Cookie' : 'PM-TabPrimary=101010010; singleSignOn=0',
'Content-Length' : '139',
'Connection' : 'keep-alive',
'cache-control' : 'no-cache',
},
body: JSON.stringify({
'grant_type' : "password",
'scope' : '*',
'client_id' : 'QKQYKIBJUXFRMGITBPKXVBWOVMFYPWWF',
'client_secret' : '2922119675d440616c9a613026663027',
'username' : this.state.username,
'password' : this.state.password,
}),
});
let res = await response.text();
if (response.status >= 200 && response.status <=300) {
this.setState({error:""});
let accessToken = res;
this.storeToken(accessToken);
console.log("res token: "+accessToken);
username = this.state.username;
Actions.Cases();
} else {
let error = res;
throw error;
}
} catch(error){
this.removeToken();
this.setState({error: error});
console.log("error" + error);
}
}
render(){
const {navigate} = this.props.navigation
return(
<View style={styles.container}>
<TextInput style={styles.inputBox}
editable={true}
onChangeText = {(username)=> this.setState({username})}
underlineColorAndroid='rgba(0,0,0,0)'
placeholder="Username"
ref='username'
returnKeyType='next'
value={this.state.username}
placeholderTextColor="#ffffff"
selectionColor="#fff"/>
<TextInput style={styles.inputBox}
editable={true}
onChangeText={(password) => this.setState({password})}
underlineColorAndroid='rgba(0,0,0,0)'
placeholder='Password'
ref='password'
returnKeyType='next'
secureTextEntry={true}
value={this.state.password}
placeholderTextColor="#ffffff"
selectionColor="#fff"/>
<TouchableOpacity style={styles.button} onPress={this.onLoginPressed.bind(this)}>
<Text style={styles.buttonText}> Log In </Text>
</TouchableOpacity>
<Text>
{this.state.error}
</Text>
</View>
)
}
}
const styles = StyleSheet.create({
container :{
flexGrow:1,
justifyContent:'center',
alignItems:'center',
},
inputBox: {
width: 300,
backgroundColor:'#C0C0C0',
borderRadius: 25,
paddingHorizontal: 16,
fontSize :14,
color: '#ffffff',
marginVertical: 13
},
buttonText: {
fontSize : 16,
fontWeight : '500',
color: '#ffffff',
textAlign:'center'
},
button: {
width:100,
backgroundColor: '#C0C0C0',
borderRadius: 40,
marginVertical: 30,
paddingVertical: 13
}
});
This is Cases.js
import React, { Component } from 'react';
import { Text, View, StyleSheet, TextInput, TouchableOpacity, AsyncStorage} from 'react-native';
import { Actions } from 'react-native-router-flux';
const ACCESS_TOKEN = 'access_token';
export default class Form extends Component {
constructor(props){
super(props);
this.state ={
grant_type : "password",
scope : "",
client_id : "",
client_secret : "",
username : "",
password : "",
error : "",
accessTokennya : "",
};
}
async storeToken(accessToken){
try{
await AsyncStorage.setItem(ACCESS_TOKEN, accessToken);
this.getToken();
}catch (error){
console.log("something where wrong")
}
}
async getToken(){
try{
let token = await AsyncStorage.getItem(ACCESS_TOKEN);
console.log("token is : "+ token)
}catch (error){
console.log("something where wrong")
}
}
async removeToken(){
try {
let token = await AsyncStorage.removeItem(ACCESS_TOKEN);
this.getToken();
} catch(error){
console.log("Something went wrong")
}
}
async onLoginPressed(){
try {
let response = await fetch('https://bpm.asihputera.or.id/asihputera/oauth2/token', {
method: 'POST',
headers: {
'Content-Type' : 'application/json',
'Accept-Encoding' : 'gzip, deflate',
'Authorization' : 'Bearer cde4e4bc600afcb604fb2ba078c60a16e29dac04',
'User-Agent' : 'PostmanRuntime/7.15.2',
'Accept' : '*/*',
'Cache-Control' : 'no-cache',
'Postman-Token' : 'ad9e715b-a2af-4f3f-86dd-11a7b6ec6037,f00ce420-e144-47ec-be83-756ec1fbc5d2',
'Host' : 'bpm.asihputera.or.id',
'Cookie' : 'PM-TabPrimary=101010010; singleSignOn=0',
'Content-Length' : '139',
'Connection' : 'keep-alive',
'cache-control' : 'no-cache',
},
body: JSON.stringify({
'grant_type' : "password",
'scope' : '*',
'client_id' : 'QKQYKIBJUXFRMGITBPKXVBWOVMFYPWWF',
'client_secret' : '2922119675d440616c9a613026663027',
'username' : this.state.username,
'password' : this.state.password,
}),
});
let res = await response.text();
if (response.status >= 200 && response.status <=300) {
this.setState({error:""});
let accessToken = res;
this.storeToken(accessToken);
console.log("res token: "+accessToken);
username = this.state.username;
Actions.Cases();
} else {
let error = res;
throw error;
}
} catch(error){
this.removeToken();
this.setState({error: error});
console.log("error" + error);
}
}
render(){
const {navigate} = this.props.navigation
return(
<View style={styles.container}>
<TextInput style={styles.inputBox}
editable={true}
onChangeText = {(username)=> this.setState({username})}
underlineColorAndroid='rgba(0,0,0,0)'
placeholder="Username"
ref='username'
returnKeyType='next'
value={this.state.username}
placeholderTextColor="#ffffff"
selectionColor="#fff"/>
<TextInput style={styles.inputBox}
editable={true}
onChangeText={(password) => this.setState({password})}
underlineColorAndroid='rgba(0,0,0,0)'
placeholder='Password'
ref='password'
returnKeyType='next'
secureTextEntry={true}
value={this.state.password}
placeholderTextColor="#ffffff"
selectionColor="#fff"/>
<TouchableOpacity style={styles.button} onPress={this.onLoginPressed.bind(this)}>
<Text style={styles.buttonText}> Log In </Text>
</TouchableOpacity>
<Text>
{this.state.error}
</Text>
</View>
)
}
}
const styles = StyleSheet.create({
container :{
flexGrow:1,
justifyContent:'center',
alignItems:'center',
},
inputBox: {
width: 300,
backgroundColor:'#C0C0C0',
borderRadius: 25,
paddingHorizontal: 16,
fontSize :14,
color: '#ffffff',
marginVertical: 13
},
buttonText: {
fontSize : 16,
fontWeight : '500',
color: '#ffffff',
textAlign:'center'
},
button: {
width:100,
backgroundColor: '#C0C0C0',
borderRadius: 40,
marginVertical: 30,
paddingVertical: 13
}
});
And then, this is a Login.js
import React, { Component } from 'react';
import { Text, View, StyleSheet, StatusBar, TouchableOpacity } from 'react-native';
import Logo from '../components/Logo';
import Form from '../components/Form';
import {Actions} from 'react-native-router-flux';
export default class Login extends Component {
render() {
return(
<View style={styles.container}>
<Logo/>
<Form type ="Login"/>
</View>
)
}
}
const styles = StyleSheet.create({
container: {
backgroundColor : '#FFFFE0',
flex: 1,
alignItems: 'center',
justifyContent: 'center'
},
signupTextCont: {
flexGrow: 1,
alignItems: 'center',
justifyContent: 'flex-end',
paddingVertical: 16,
flexDirection: 'row'
},
signupText:{
color: 'rgba(255,255,255, 0.7)',
fontSize: 16,
paddingVertical: 30,
marginVertical: 30
},
signupButton: {
color: '#ffffff',
fontSize: 16,
fontWeight:'500'
}
});
I hope i get a solution at here :D thank you

Try using this in : Login.js
render() {
return(
<View style={styles.container}>
<Logo navigation = {this.props.navigation}/>
<Form navigation = {this.props.navigation}
type ="Login"/>
)

In your Form.js, with Actions.Cases(); you can pass the values you want to pass as
Actions.Cases({"userName" :this.state.username ,"Password: : this.state.password})
In Cases.js file when you want to get the username just write
this.props.userName
whatever you want to get from one page to other page just need to add
this.props.(key which you've passed in last page)

Related

Want to transfer login status from store to Login Screen for wrong credentials identification

I have to React Native IOS App with Login Screen for users. In the store auth, I am getting string output from Login API as 'success' or 'Login Failed'.I want to transfer this login status to Login Screen, to tell the user about the wrong credentials. Below is the auth store:
auth.js:
export const LOGIN ='LOGIN';
export const login=(textemailid,textpassword) =>{
const formData = new FormData();
formData.append('txtUemail',textemailid);
formData.append('txtUpass',textpassword);
return async dispatch =>{
await fetch('https:/-------------------/login.php',
{
method:'post',
headers: {
'Content-Type': 'application/json',
'Accept': 'application/json',
},
body: formData
})
.then(res => res.text())
.then(
(loginresult) =>{
var login = loginresult.replace('\r\n\r\n\r\n\t\r\n\t\r\n\t','');
console.log('loginstatus is '+login);
}).catch(err =>{
console.log(err);
})
dispatch({type:LOGIN,loginStatus:login});
}
}
I want to transfer the 'login' value to Login Screen using navigation. Below is the LoginScreen code:
LoginScreen.js:
import React,{useEffect} from 'react';
import { ActivityIndicator,StyleSheet, Text, View
,KeyboardAvoidingView,TouchableOpacity,Image} from "react-native";
import { Button } from 'react-native-elements';
import { ScrollView } from "react-native-gesture-handler";
import { HelperText,TextInput } from 'react-native-paper';
import { useDispatch } from 'react-redux';
import * as authActions from '../../store/actions/auth';
import Icon from 'react-native-vector-icons/FontAwesome5';
import AsyncStorage from '#react-native-async-storage/async-
storage'
import Toast from 'react-native-root-toast';
const LoginScreen = ({route}) => {
const [textemailid, setTextEmailId] = React.useState('');
const [textpassword, setTextPassword] = React.useState('');
const [isLoading,setIsLoading] = React.useState(false);
const [error, setError] = React.useState('');
const dispatch = useDispatch();
const loginStatus1 = useSelector(state =>
state?.auth?.login_Status); **getting login_Status from auth reducer**
//console.log(state);
console.log('login status is '+loginStatus1)
const loginHandler = async () => {
let action
action = authActions.login(
textemailid,
textpassword
);
setError(null);
setIsLoading(true);
try{
dispatch(action);
console.log('login status is '+loginStatus);
if(loginStatus === 'Login Failed'){
let toast_success = Toast.show('Wrong Credentials');
setIsLoading(false);
}
else if(loginStatus === 'success'){
props.navigation.navigate({routeName:'Home'});
}
} catch(err){
setError(err.message);
console.log(err.message);
setIsLoading(false);
}
};
return(
<KeyboardAvoidingView style={styles.container}>
<ScrollView>
<View style={styles.container}>
<View style={styles.subView}>
<Image
style={{flex:1, height: 100, width: 100,alignSelf:'center',bottom:350}}
source={require('../../assets/profile1.png')}
resizeMode="contain"
/>
<View style={styles.welcometextview}>
<Text style={styles.welcometext}>Welcome!</Text>
{/* <Loader loading={isLoading} color="#ff66be" title='Loading'/> */}
</View>
<View style={styles.textinputemailview}>
<TextInput
underlineColor='grey'
style={styles.textinputemail}
label='Email'
keyboardType="email-address"
editable={true}
autoCapitalize = 'none'
value={textemailid}
theme={{ colors: { placeholder: "#f5f5f5", background: "transparent", text:
'green', primary: '#D43790' } }}
onChangeText={textemailid=>setTextEmailId(textemailid)}>
</TextInput>
</View>
<View style={styles.textinputpasswordview} >
<TextInput style={styles.textinputpassword}
underlineColor='grey'
label='Password'
autoCapitalize = 'none'
editable={true}
value={textpassword}
onChangeText={textpassword => setTextPassword(textpassword)}
theme={{ colors: { placeholder: "#f5f5f5", background: "transparent",text:
'green',primary: '#D43790' } }}>
</TextInput>
</View>
<View style={styles.loginbuttonview}>
{isLoading ? (
<ActivityIndicator size='small' color='green'/>
) :
(
<Button buttonStyle={{
backgroundColor: "#EB4207"
}}
containerStyle={{
marginTop: 12,
width: "50%"
}}
onPress={
() => { loginHandler();
}}
title='Log in'/>
)}
</View>
</View>
<TouchableOpacity style={styles.textforgotpasswordview} onPress=.
{()=>props.navigation.navigate('ForgotPasswordPage')}>
<Text style={styles.textforgotpassword}>Forgot your password?</Text>
</TouchableOpacity>
<TouchableOpacity style={styles.textregisterview} onPress=.
{()=>props.navigation.navigate('SignUp')} >
<Text style={styles.textregister}>Not a member?Sign up now</Text>
</TouchableOpacity>
</View>
</ScrollView>
</KeyboardAvoidingView>
)}
const styles = StyleSheet.create({
container: {
backgroundColor: '#0B0B45',
flex:1,
},
subView: {
backgroundColor: '#1D1F33',
height: 750,
marginTop: 150,
borderTopRightRadius: 40,
borderTopLeftRadius: 40,
},
welcometextview:{
bottom:'80%',
justifyContent:'center',
alignItems:'center'
},
welcometext:{
fontWeight:'bold',
color:'grey',
fontSize:20,
},
textinputemailview:{
position:'absolute',
top:'23%',
width:'80%',
alignSelf:'center'
},
textinputemail:{
backgroundColor:'transparent',
fontWeight:'bold',
fontSize:20,
},
textinputpasswordview:{
position:'absolute',
top:'35%',
width:'80%',
alignSelf:"center"
},
textinputpassword:{
backgroundColor:'transparent',
fontWeight:'bold',
fontSize:20,
},
textregisterview:{
position:'absolute',
top:'75%',
alignSelf:'center'
},
textregister:{
color: "#EB4207",
fontSize: 20,
fontWeight: "bold",
textDecorationLine: 'underline'
},
textforgotpasswordview:{
position:'absolute',
alignSelf:'center',
bottom:'33%'
},
textforgotpassword:{
color: "white",
fontSize: 20,
fontWeight: "bold",
},
loginbuttonview:{
bottom:'45%',
justifyContent:'center',
alignItems:'center'
},
});
export default LoginScreen;
Below is the auth reducer:
auth.js:
import { GETDEVICEINFO, LOGIN,LOGOUT } from '../actions/auth';
const initialState = {
mobileno: null,
login_Status:null,
availableDevice:[],
};
export default (state = initialState,action) => {
switch(action.type){
case LOGIN:
return {
login_Status : action.loginStatus
};
case GETDEVICEINFO:
return {
availableDevice:action.devices
}
case LOGOUT:
return initialState;
default: return state;
}
}
I don't think async storage will work here because I don't want to persist data but only want to get data from auth store and also using AsyncStorage will not flush old data, it stores data till u logout and login.
After running the above code, I am getting the whole function as below:
login status is function login(textemailid, textpassword) {
var formData = new FormData();
formData.append('txtUemail', textemailid);
formData.append('txtUpass', textpassword);
return function _callee(dispatch) {
return _regenerator.default.async(function _callee$(_context) {
while (1) {
switch (_context.prev = _context.next) {
case 0:
_context.next = 2;
return _regenerator.default.awrap(fetch('https:--------
-/login.php', {
method: 'post',
headers: {
'Content-Type': 'application/json',
'Accept': 'application/json'
},
body: formData
}).then(function (res) {
return res.text();
}).then(function (loginresult) {
var login =
loginresult.replace('\r\n\r\n\r\n\t\r\n\t\r\n\t', '');
console.log('login1 is ' + login);
saveDataToStoragelogin(login, textemailid);
}).catch(function (err) {
console.log(err);
}));
case 2:
dispatch({
type: LOGIN,
loginStatus: login
});
case 3:
case "end":
return _context.stop();
}
}
}, null, null, null, Promise);
};
Can anyone say how to get only login_Status string. Thanks in Advance?
I would try to change
try{
props.navigation.navigate('LoginScreen', {
paramKey: login,
})
to
try{
navigation.navigate('LoginScreen', {
paramKey: login,
})
No need to pass navigation prop to auth store. When you dispatch({type:LOGIN}) with payload store that state in reducer.Get the State using UseSelector.
For example you are in Screen A and did login Api call and store api response data in reducer. In same screen use useSelector to get the api data response from reducer. based on response type navigate to respected screens. Don't place api call in reducers.
Please check this example https://github.com/raduungurean/react-native-redux-auth-login-logout-example

How to get Access Token after Login Credential from JSON API in react-native

enter image description here I want to fetch the data of User profile after User Login.I am able to save User Token with
isLoggedIn key but I can't store the token in this code.I just want to fetch the URL data with the
help of User Token but I get an Alert message "invalid token" when i click on User Profile Button
so I cannot access the URL data attributes.Please check my code.
import React, { Component } from 'react';
import { StyleSheet, View, Text, SafeAreaView, Image,
ScrollView,AsyncStorage,TouchableOpacity,ActivityIndicator,
} from 'react-native';
class UserProfile extends Component {
constructor(props) {
super(props);
this.state = {
dataSource : [] ,
isLoading : true,
};
}
componentDidMount() {
this.fetchUserData()
}
async fetchUserData() {
const DEMO_TOKEN = await AsyncStorage.getItem("isLoggedIn");
if (DEMO_TOKEN != null) {
try {
console.log('tokenresponse', DEMO_TOKEN)
const url = "http://104.197.28.169:3000/userProfile";
const header = {
method: "GET",
headers: {
Authorization: " Bearer" + DEMO_TOKEN,
},
};
const response = await fetch(url, header);
const jsonResponse = await response.json();
console.log('gerwgewrhe',jsonResponse);
this.setState({
dataSource: jsonResponse,
isLoading: false,
});
} catch (error) {
console.log(error);
}
}
}
render() {
{
return (
this.state.isLoading
?
<View style={{ flex: 1, justifyContent: 'center', alignItems:
'center' }}>
<ActivityIndicator size="large" color="#330066" />
</View>
:
<View style={styles.container}>
<View style={styles.name}>
<Text style={styles.label}>Employee ID:</Text>
<Text style={styles.Shable}>
{this.state.dataSource.data.empId}
</Text>
</View>
<View style={styles.name}>
<Text style={styles.label}>First Name:</Text>
<Text style={styles.Shable}>
{this.state.dataSource.data.firstName}
</Text>
</View>
<View style={styles.name}>
<Text style={styles.label}>Last Name:</Text>
<Text style={styles.Shable}>
{this.state.dataSource.data.lastName}
</Text>
</View>
<View style={styles.name}>
<Text style={styles.label}>Gender:</Text>
<Text style={styles.Shable}>
{this.state.dataSource.data.gender}
</Text>
</View>
<View style={styles.name}>
<Text style={styles.label}>Mobile Number:</Text>
<Text style={styles.Shable}>
{this.state.dataSource.data.contactNo}
</Text>
</View>
</View>
);
}
}
}
export default UserProfile ;
Here is my URL data.
{
"message": "user profile",
"data": {
"id": 39,
"location": "Bikaner",
"empId": "Dd1",
"firstName": "Divyanshu",
"lastName": "Gahlot",
"dateOfBirth": "2020-04-16",
"gender": "Male",
"maritalStatus": "Unmarried",
"contactNo": 9864676468,
"residenceAddress": "Jaipur",
"emailId": "divyanshu#gmail.com",
}
"status": 1
}
This is my login and Authloading Screen.
CheckTextInput = async () => {
await fetch('http://104.197.28.169:3000/auth/login?', {
method: 'POST',
headers: {
'Accept': 'application/json',
'Content-Type': 'application/json',
},
body: JSON.stringify({
email: this.state.TextInputEmail,
password: this.state.TextInputPassword,
})
}).then((response) => response.json())
.then((responseJson) => {
if(responseJson.message === "user logged in successfully")
{
alert('User login Successfully')
console.log('Token' , responseJson.token
const Token = responseJson.token
AsyncStorage.setItem('isLoggedIn',responseJson.token);
this.props.navigation.navigate('drawernavigation');
}
else{
alert(responseJson.message);
}
}).done()
}
class AuthLoadingScreen extends Component {
constructor(props) {
super(props);
this.loadData();
}
render() {
return (
<View style={{ flex: 1, justifyContent: 'center', alignItems: 'center', }}>
<ActivityIndicator />
<StatusBar barStyle="default" />
</View>
);
}
loadData = async () => {
const isLoggedIn = await AsyncStorage.getItem('isLoggedIn')
this.props.navigation.navigate(isLoggedIn != 'token' ? 'loginnavigator' :
'drawernavigation')
}
}
export default createAppContainer(createSwitchNavigator(
{
AuthLoading: AuthLoadingScreen,
loginnavigator: AppNavigator,
drawernavigation : NaviNavi,
forgotstack: AuthStack,
monthlyattendance: attendacnemonthly,
},
)
);

Invariant Violantion expected string, getting object--from php page that echos a string

I'm extremely new to React Native. I'm logging in a user. Here's the tutorial I'm going off. I had to use XMLHttpRequest instead of fetch because I couldn't get it to pass the POST parameters correctly. The PHP page it posts to just echos out the userID before returning. It's not returning a json string or anything.
I'm logging in the user and using
this.setState({ userID: request.responseText });
to keep track of the userID. This line is giving me the Invariant Violation error, that it expects a string and I'm giving it an object.
App.js ( I included the commented out fetch in case you saw any obvious answers)
import React, { Component } from 'react'
import { View, Text, Alert, Button, TextInput, TouchableOpacity } from 'react-native';
import Home from './Home';
export default class App extends Component{
state = {
email: '',
pwd: '',
auth_token: '',
userID: ''
}
Login = async () => {
var request = new XMLHttpRequest();
var params = "email=" + this.state.email + "&pwd=" + this.state.pwd;
request.onreadystatechange = (e) => {
if (request.readyState !== 4) {
return;
}
if (request.status === 200) {
console.log('success', request.responseText);
Alert.alert(request.responseText); //this is returning the correct value
if(request.responseText != "ERROR"){
this.setState({ userID: request.responseText });
Alert.alert("Welcome", " You have succesfully logged in");//also returning
}else{
Alert.alert("Oh, no!", " There was a problem");
}
} else {
console.warn('error');
}
};
request.open('POST', 'https://mysitexzy.com/wLoginCE');
request.send(params);
/*
fetch('https://mysitexzy.com/wLoginCE', {
method: 'post',
headers: {
Accept: 'application/json',
// 'Content-Type': 'application/json',
},
body: JSON.stringify({
// "provider": "username",
"email": this.state.email,
"pwd": this.state.pwd
})
}).then((response) => response.json())
.then((res) => {
if(typeof(res.message) != "undefined"){
Alert.alert("Error", "Error: "+ res.message);
}
else{
this.setState({ userID: response });
Alert.alert("Welcome", " You have succesfully logged in");
}
}).catch((error) => {
console.error(error);
});
*/
}
render(){
//If auth token is not present
if(this.state.userID==''){
return(
<View style={{
flex: 1,
flexDirection: 'column',
justifyContent: 'center',
alignItems: 'stretch',
}}>
<TextInput
placeholder="Enter User name"
onChangeText={ TextInputValue =>
this.setState({email : TextInputValue }) }
underlineColorAndroid='transparent'
style={
{
textAlign: 'center',
width: '90%',
marginBottom: 7,
height: 40,
borderRadius: 5 ,
fontSize: 20,
}
}
/>
<TextInput
placeholder="Enter password"
onChangeText={ TextInputValue =>
this.setState({pwd: TextInputValue }) }
underlineColorAndroid='transparent'
secureTextEntry={true}
style={
{
textAlign: 'center',
width: '90%',
marginBottom: 7,
height: 40,
borderRadius: 5 ,
fontSize: 20,
}
}
/>
<TouchableOpacity onPress={this.Login.bind(this)}>
<View style={{height: 50, backgroundColor:
'#cc0066',justifyContent: 'center',
alignItems: 'center',}}>
<Text style={{
fontSize: 20,
color: '#FFFFFF',
}}>
Login </Text>
</View>
</TouchableOpacity>
</View>
);
}
/* Checking if the auth token is not empty directly sending the user to Home screen */
else{
return(
<Home />
);
}
}
}
Home.js is blank per the instructions in the tutorial.

React-native-multiple-select: Cannot read the property 'getSelectedItemsExt' of undefined

I am building an App and referring this link
i implemented same code for my App, but i am getting error "Cannot read the property 'getSelectedItemsExt' of undefined".
One more error is "submit" button is also not showing up. I have tried all the ways but failed.
import React, { Component } from 'react';
import { AppRegistry, StyleSheet, TextInput, View, ListView, Alert, Button, Platform, ToastAndroid, TouchableOpacity, ActivityIndicator, Text, Picker, ScrollView }
from 'react-native';
import { StackNavigator } from 'react-navigation';
import MultiSelect from 'react-native-multiple-select';
class manage_publishers extends Component {
static navigationOptions = {
title: 'Manage Publishers',
};
constructor() {
super()
this.state = {
isLoading: true,
selectedPublishers1:[],
publishersByCategory: [],
publishersByClient: [],
publishersByGroup: [],
dataSource:[]
}
}
componentDidMount()
{
const base64 = require('base-64');
fetch('APIURL'+this.props.navigation.state.params.id,
{
method: 'GET',
headers: {
'Accept': 'application/json',
'Content-Type': 'application/json',
"Authorization": "Basic " + base64.encode("ABC:XYZ")
}
}).then((response) => response.json()
)
.then((responseJson) => {
this.setState({
categories: responseJson.PublisherByCategory,
}, function () {
});
})
.catch((error) => {
console.log("error in category");
console.log(error);
});
}
onSelectedPublishersByCategoryChange = (publishersByCategory) => {
console.log(publishersByCategory);
this.setState({ publishersByCategory });
}
render() {
const { navigate } = this.props.navigation;
if (this.state.isLoading) {
return (
<View style={{ flex: 1, paddingTop: 20 }}>
<ActivityIndicator />
</View>
);
}
return ([
<View style={{flex: 1,paddingTop: (Platform.OS === 'ios') ? 20 : 20, padding: 5}}>
<Text style={{ padding: 5, fontSize: 35, backgroundColor: '#2196F3', marginBottom: 7 }}>
Manage Publishers
</Text>
<MultiSelect
items={this.state.categories}
uniqueKey="id"
ref={(component) => { this.multiSelect = component }}
onSelectedItemsChange={this.onSelectedPublishersByCategoryChange}
selectedItems={this.state.publishersByCategory}
selectText="Publishers by Category"
searchInputPlaceholderText="Search Publisher..."
onChangeInput={ (text)=> console.log(text)}
altFontFamily="ProximaNova-Light"
tagRemoveIconColor="#CCC"
tagBorderColor="#CCC"
tagTextColor="#CCC"
selectedItemTextColor="#CCC"
selectedItemIconColor="#CCC"
itemTextColor="#000"
displayKey="name"
searchInputStyle={{ color: '#CCC' }}
submitButtonColor="#CCC"
submitButtonText="Submit"
/>
</View>,
<View>
{this.multiSelect.getSelectedItemsExt(selectedItems)}
</View>
]);
}
}
});
module.exports = manage_publishers;
Please have a look at this and provide me solution, I'll be very thankful .
I had that same issue, and I solved adding a AND condition:
{this.multiSelect && this.multiSelect.getSelectedItemsExt(selectedItems)}
If you are using functional components you can do like this,
create ref like this,
const multiSelect = useRef(null)
Access the getSelectedItemsExt function like this,
<View>
{multiSelect.current && multiSelect.current.getSelectedItemsExt &&
multiSelect.current.getSelectedItemsExt(countries)}
</View>
It happened because you called a method before the reference has been set.
Use this code:
<View>
{ this.multiSelect ? this.multiSelect.getSelectedItemsExt(selectedItems) : null}
</View>
Reference to this issue:
https://github.com/toystars/react-native-multiple-select/issues/58#issuecomment-364136438

POST data request on server via react native?

Basically what i'm trying to do is, on click of login button it should take my input data and check whether the data is valid for authentication and send back response to user and display on UI. After authentication it should be redirected to home screen. I tried using fetch but it's not working. Below is the code:
import React, { Component } from 'react';
import {
AppRegistry,
Text,
Image,
View,
StyleSheet,
TextInput,
Linking,
Alert,
Navigator
} from 'react-native';
import { Button } from 'react-native-elements';
import t from 'tcomb-form-native';
const Form = t.form.Form;
// here we are: define your domain model
const Email = t.subtype(t.Str, (email) => {
const reg = /^(([^<>()\[\]\\.,;:\s#"]+(\.[^<>()\[\]\\.,;:\s#"]+)*)|(".+"))#((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/;
return reg.test(email);
});
const LoginFields = t.struct({
username: Email, // a required string
password: t.String, // a required string
});
const options = {
fields: {
password: {
type: 'password',
placeholder: 'Password',
error: 'Password cannot be empty'
},
username: {
placeholder: 'e.g: abc#gmail.com',
error: 'Insert a valid email'
}
}
}; // optional rendering options (see documentation)
export class ChildComponent extends Component {
render() {
if(this.props.result) {
var res = this.props.result.map((item, i) => {
return(
<Text key={i}>{item.useremail}</Text>
)
})
}
return (
<View>
{res}
</View>
)
}
}
export default class Login extends Component {
constructor(props) {
super(props);
this.state = {
buttonState: true,
value: {}
}
}
_onSubmit() {
const value = this.refs.form.getValue();
if (value) { // if validation fails, value will be null
console.log(value);
// value here is an instance of LoginFields
}
componentDidMount() {
fetch('http://192.168.100.160:6016/admin/login', {
method: 'POST',
headers: {
'Accept': 'application/x-www-form-urlencoded',
'Content-Type': 'application/x-www-form-urlencoded',
},
body: JSON.stringify({
useremail: 'kirti#pws.com',
userpassword: '1234',
})
})
.then((response) => response.json())
.then((responseJson) => {
this.setState ({
data: responseJson.admin/login
})
})
}
this.props.navigator.push({
id: 'Home'
});
}
onChange = () => {
const value = this.refs.form.getValue();
if(value) {
this.setState({
value,
buttonState: false
});
}
}
render() {
return (
<View style={styles.container}>
<View style={styles.header}>
</View>
<View style={styles.content}>
<Text style={styles.contentHeader}>
Pateast Login
</Text>
<View style={styles.loginFormContent}>
<Form
ref="form"
type={LoginFields}
options={options}
value={this.state.value}
onChange={this.onChange}
/>
<Text style={{color: 'blue', marginBottom: 10}}
onPress={() => Linking.openURL('https://www.google.co.in')}>
Forgot Password?
</Text>
<Button
raise
icon={{name: 'key', type: 'octicon'}}
onPress={this._onSubmit.bind(this)}
title="Login"
disabled={this.state.buttonState}
accessibilityLabel="Ok, Great!"
/>
</View>
</View>
<View style={styles.footer}>
</View>
<ChildComponent status={this.state.status} result={this.state.data} />
</View>
);
}
}
const styles = StyleSheet.create(
{
container: {
flex: 1
},
contentHeader: {
// fontFamily: 'sans-serif-condensed',
fontWeight: 'bold',
fontSize: 40,
alignSelf: 'center',
marginBottom: 30
},
header : {
flex: 0.5,
backgroundColor: '#008080'
},
content: {
flex: 10,
backgroundColor: '#f8f8ff',
justifyContent: 'center'
},
loginFormContent: {
marginHorizontal: 20
},
footer: {
flex: 0.5,
backgroundColor: '#008080'
},
loginText: {
fontSize: 20,
marginBottom: 10
},
inputFields: {
fontSize: 20,
borderStyle: 'solid',
borderColor: '#000000',
borderRadius: 30,
marginBottom: 10
}
}
);
you were just one step away from your goal. The only thing you have to change is your body object in your post request. This object has to be a FormData https://developer.mozilla.org/de/docs/Web/API/FormData
Try to set the body like this:
let data = new FormData();
data.append("useremail", 'kirti#pws.com');
data.append("userpassword", '1234');
After that your fetch request should look like this:
fetch('http://192.168.100.160:6016/admin/login', {
method: 'POST',
headers: {
'Accept': 'application/x-www-form-urlencoded',
'Content-Type': 'application/x-www-form-urlencoded',
},
body: data
}
...