React Native AXIOS method GET response.data shows null - javascript

Trying to get data on React Native native using axios method GET and local IP.
Running the URL on localhost using XAMPP works fine on the web.
But when trying to get data using api call on React Native, it's showing response.data as null on console.log()
The following are the code snippet below:
The sign in screen successfully shows the user token and user type on console.log().
SignInScreen.js
import React, { Component } from 'react';
import { StyleSheet, ScrollView, View, TextInput, } from 'react-native';
import { mapping, light as lightTheme, dark as darkTheme } from '#eva-design/eva';
import { ApplicationProvider, Layout, Text, Input, Button } from 'react-native-ui-kitten';
import Constants from '../constants/Constants';
import axios from 'axios';
import AsyncStorage from '#react-native-community/async-storage';
export default class SignInScreen extends Component {
static navigationOptions = {
title: 'Sign In',
};
constructor(props) {
super(props);
this.state = {
userName: 'freelancer',
password: 'password',
}
}
login() {
console.log('Sign In Pressed');
var self = this;
axios({
method: 'post',
url: Constants.API_URL + 'auth/login/',
data: {
user_name: this.state.userName,
password: this.state.password,
},
headers: {
'X-API-KEY': 'zzzz',
},
})
.then(function (response) {
if (response.data) {
AsyncStorage.setItem('my_token', response.token);
AsyncStorage.setItem('u_type', response.type);
//self.props.navigation.navigate('UserHome');
self.props.navigation.navigate('Freelancer');
console.log("Login Sucessful (response.data) ===> ", response.data);
} else {
console.log('Login attempt Failed');
}
})
.catch(function (error) {
console.log(error)
console.log('Error Response', error.response)
});
}
render() {
const { navigate } = this.props.navigation;
return (
<ApplicationProvider
mapping={mapping}
theme={lightTheme}>
<Layout style={styles.container} level='1'>
<ScrollView>
<Text style={styles.text} category='h4'>Sign Up with Email</Text>
<TextInput label={'USERNAME'}
placeholder={'username'}
autoCapitalize='none'
style={styles.input}
onChangeText={userName => this.setState({ userName })}
value={this.state.userName} />
<TextInput label={'PASSWORD'}
placeholder={'Password'}
autoCapitalize='none'
style={styles.input}
onChangeText={password => this.setState({ password })}
value={this.state.password} />
<Button style={styles.button} onPress={() => this.login()}>SIGN IN</Button>
</ScrollView>
</Layout>
</ApplicationProvider>
);
}
}
const styles = StyleSheet.create({
button: {
marginTop: 15,
marginLeft: 16,
marginRight: 16
},
container: {
flex: 1,
},
input: {
marginLeft: 16,
marginRight: 16,
marginBottom: 15
},
text: {
marginVertical: 16,
textAlign: 'center'
},
});
However, on FreelancerScreen the response.data is showing null.
FreelancerScreen.js
import React, { Component } from 'react';
import { View, Text, StyleSheet, FlatList, TouchableOpacity } from 'react-native';
import axios from 'axios';
import Constants from '../constants/Constants';
import AsyncStorage from '#react-native-community/async-storage';
export default class FreelancerScreen extends Component {
constructor(props) {
super(props);
this.state = {
dataSource: [],
//-test
totalBooked: null,
dateStart: null,
};
console.log('Constructor()');
}
componentDidMount() {
this.getAppointmentList();
console.log('ComponentDidMount()')
}
getAppointmentList = () => {
var self = this;
axios({
method: 'get',
url: Constants.API_URL + 'appointment_f/flist/',
responseType: 'json',
headers: {
'X-API-KEY': 'zzzz',
Authorization: AsyncStorage.getItem('my_token'),
},
})
.then(function (response) {
console.log('Response Data: ', response.data);
})
.catch(function (error) {
console.log('Error Response: ', error.response);
});
};
clearAsyncStorage = async () => {
AsyncStorage.clear();
this.props.navigation.navigate('SignIn');
console.log('Logged Out.')
}
render() {
const { dataSource } = this.state;
return (
<View>
<Text style={{ marginLeft: 20 }}> FreelancerScreen </Text>
<TouchableOpacity onPress={() => this.clearAsyncStorage()}>
<Text style={{ margin: 20, fontSize: 25, fontWeight: 'bold' }}>LogOut</Text>
</TouchableOpacity>
{<FlatList
data={dataSource}
renderItem={({ item }) => {
return (
<View>
<Text style={{ marginLeft: 20 }}>date_start: {item.date_start}</Text>
<Text style={{ marginLeft: 20 }}>total_booked: {item.total_booked}</Text>
</View>
);
}}
/>}
</View>
);
}
};
/*data: {
total_booked: this.state.totalBooked,
date_start: this.state.dateStart,
},*/

Related

Not connecting to Stripe API

I am coding a stripe React Native gateway and I was coding stripe connections to the API. I used the API in connecting to Stripe but it says that I am not connected to the API. This is mainly in two files: ShopScreen.js and index.js.
Here is ShopScreen.js:
import {PureComponent} from 'react';
import stripe from 'tipsi-stripe';
import Button from '../components/components/Button';
import {
ActivityIndicator,
TouchableOpacity,
TextInput,
Image,
ImageBackground,
} from 'react-native';
import * as React from 'react';
import axios from 'axios';
import {WebView} from 'react-native-webview';
import {
SafeAreaView,
StyleSheet,
ScrollView,
View,
Text,
StatusBar,
FlatList,
} from 'react-native';
stripe.setOptions({
publisherKey: 'pk_test_HWcOeGStIfoP98VZkHRIJUmO00E1eZyuQG',
});
class ShopScreen extends React.Component {
constructor(props) {
super(props);
this.state = {
search: '',
data: [],
};
}
handleSearch = (text) => {
this.setState({search: text});
};
componentDidMount() {
axios
.get('http://localhost:3000')
.then((response) => {
this.setState({
data: response.data,
});
})
.catch(function (err) {
alert(err);
});
}
static title = 'Card Form';
state = {
loading: false,
token: null,
};
handleCardPayPress = async () => {
try {
this.setState({loading: true, token: null});
const token = await stripe.paymentRequestWithCardForm({
// Only iOS support this options
smsAutofillDisabled: true,
requiredBillingAddressFields: 'full',
prefilledInformation: {
billingAddress: {
name: 'Vaibhav Herugu',
line1: '2 Darryl Drive',
line2: '',
city: 'Morganville',
state: 'NJ',
country: 'USA',
postalCode: '07751',
email: 'vherugu#gmail.com',
},
},
});
this.setState({loading: false, token: token});
} catch (error) {
this.setState({loading: false});
}
};
makePayment = async () => {
this.setState({loading: true});
axios({
method: 'POST',
url:
'https://us-central1-localmainstreet-b0144.cloudfunctions.net/completePaymentWithStripe',
data: {
amount: 0,
currency: 'usd',
token: this.state.token,
},
}).then((response) => {
console.log(response);
this.setState({loading: false});
});
};
render() {
const {loading, token} = this.state;
console.log('##data', this.state.data);
const Item = ({user}) => {
console.log('##item', user);
return (
<View>
<View style={styles.viewforFlatList}>
<View style={styles.viewforButton}>
<Text style={styles.businessNameStyle}>{user.item.bname}</Text>
<View style={styles.container}>
<Button
style={styles.buttons1}
text="Buy Now"
loading={loading}
onPress={this.handleCardPayPress}
/>
<View style={styles.token}>
{token && (
<>
<Text style={styles.instruction}>
Token: {this.state.token}
</Text>
{this.makePayment}
</>
)}
</View>
</View>
</View>
</View>
<Text style={styles.businessDescandEmailStyle}>
{user.item.bdesc}
</Text>
<Text style={styles.businessDescandEmailStyle}>
Email: {user.item.email}
</Text>
<Text style={styles.phoneNumberStyle}>
Phone Number: {user.item.phonenum}
</Text>
</View>
);
};
const {navigate} = this.props.navigation;
return (
<View style={styles.viewForSearch}>
<StatusBar barStyle="dark-content" />
<View style={styles.viewforButton}>
<TextInput
style={styles.input2}
underlineColorAndroid="transparent"
placeholder="Business Category/Name"
placeholderTextColor="#000000"
autoCapitalize="none"
onChangeText={this.handleSearch}
/>
<TouchableOpacity style={styles.buttons}>
<Text style={styles.buttonText}>Search</Text>
</TouchableOpacity>
</View>
<TouchableOpacity
style={styles.buttonsUnderLogin}
onPress={() => {
navigate('Help');
}}>
<Text style={styles.buttonTextForSignUp}>Help</Text>
</TouchableOpacity>
{/* <WebView
source={{ uri: 'https://reactnative.dev' }}
style={{ marginTop: 20 }}
/> */}
<View style={styles.FlatList}>
<FlatList
data={this.state.data}
renderItem={(user) => <Item user={user} />}
keyExtractor={(user) => user.id}
/>
</View>
</View>
);
}
}
export default ShopScreen;
(styles not shown for ShopScreen.js)
and here is index.js:
const functions = require('firebase-functions');
const stripe = require('stripe')('SECRET-KEY');
exports.completePaymentWithStripe = functions.https.onRequest(
(request, response) => {
stripe.charges
.create({
amount: request.body.amount,
currency: request.body.currency,
source: 'tok_mastercard',
})
.then((charge) => {
response.send(charge);
return charge;
})
.catch((error) => {
console.log(error);
});
},
);
(where it says SECRET-KEY I added my secret key)
This is supposed to connect to Stripe and process my payment. Instead, it shows,
I went to the docs and tried using what it said to use, but it didn't work, so I deleted it.
This is my problem. Thanks.
hey the issue is that you haven't added the token with your request
exports.completePaymentWithStripe = functions.https.onRequest(
(request, response) => {
stripe.customers.create(req.body.token).then(customer => {
stripe.charges
.create({
amount: request.body.amount,
currency: request.body.currency,
source: 'tok_mastercard',
customer: customer.id
})
})
.then((charge) => {
response.send(charge);
return charge;
})
.catch((error) => {
console.log(error);
});
},
);

React Native Axios getting NULL response.data using GET method

Trying to get data on React Native native using axios method GET and local IP.
Running the URL on localhost using XAMPP works fine on the web.
But when trying to get data using api call on React Native, it's showing response.data as null on console.log()
Problem:
the response.data on FreelancerScreen.js shows null. So, if anyone can help with this issue that would be great.
Code snippet provided below:
SignInScreen.js
import React, { Component } from 'react';
import { StyleSheet, ScrollView, View, TextInput, } from 'react-native';
import { mapping, light as lightTheme, dark as darkTheme } from '#eva-design/eva';
import { ApplicationProvider, Layout, Text, Input, Button } from 'react-native-ui-kitten';
import Constants from '../constants/Constants';
import axios from 'axios';
import AsyncStorage from '#react-native-community/async-storage';
export default class SignInScreen extends Component {
static navigationOptions = {
title: 'Sign In',
};
constructor(props) {
super(props);
this.state = {
userName: 'freelancer',
password: 'password',
}
}
login() {
console.log('Sign In Pressed');
var self = this;
axios({
method: 'post',
url: Constants.API_URL + 'auth/login/',
data: {
user_name: this.state.userName,
password: this.state.password,
},
headers: {
'X-API-KEY': 'xxxxx',
},
})
.then(function (response) {
if (response.data) {
AsyncStorage.setItem('my_token', response.data.token);
AsyncStorage.setItem('u_type', response.data.type);
//self.props.navigation.navigate('UserHome');
self.props.navigation.navigate('Freelancer');
console.log("Login Sucessful (response.data) ===> ", response.data);
} else {
console.log('Login attempt Failed');
}
})
.catch(function (error) {
console.log(error)
console.log('Error Response', error.response)
});
}
render() {
const { navigate } = this.props.navigation;
return (
<ApplicationProvider
mapping={mapping}
theme={lightTheme}>
<Layout style={styles.container} level='1'>
<ScrollView>
<Text style={styles.text} category='h4'>Sign Up with Email</Text>
<TextInput label={'USERNAME'}
placeholder={'username'}
autoCapitalize='none'
style={styles.input}
onChangeText={userName => this.setState({ userName })}
value={this.state.userName} />
<TextInput label={'PASSWORD'}
placeholder={'Password'}
autoCapitalize='none'
style={styles.input}
onChangeText={password => this.setState({ password })}
value={this.state.password} />
<Button style={styles.button} onPress={() => this.login()}>SIGN IN</Button>
</ScrollView>
</Layout>
</ApplicationProvider>
);
}
}
const styles = StyleSheet.create({
button: {
marginTop: 15,
marginLeft: 16,
marginRight: 16
},
container: {
flex: 1,
},
input: {
marginLeft: 16,
marginRight: 16,
marginBottom: 15
},
text: {
marginVertical: 16,
textAlign: 'center'
},
});
FreelancerScreen.js
import React, { Component } from 'react';
import { View, Text, StyleSheet, FlatList, TouchableOpacity } from 'react-native';
import axios from 'axios';
import Constants from '../constants/Constants';
import AsyncStorage from '#react-native-community/async-storage';
export default class FreelancerScreen extends Component {
constructor(props) {
super(props);
this.state = {
dataSource: [],
//-test
totalBooked: null,
dateStart: null,
};
console.log('Constructor()');
}
componentDidMount() {
this.getAppointmentList();
console.log('ComponentDidMount()')
}
getAppointmentList = () => {
let self = this;
AsyncStorage.getItem('my_token').then((keyValue) => {
console.log('Freelancer Screen (keyValue): ', keyValue); //Display key value
axios({
method: 'get',
url: Constants.API_URL + 'appointment_f/flist/',
responseType: 'json',
headers: {
'X-API-KEY': 'xxxxx',
//Authorization: `Bearer ${keyValue}`,
Authorization: keyValue,
},
})
.then(function (response) {
console.log('response.data: ===> ', response.data)
console.log('Response: ', response);
self.setState({
dataSource: response.data,
})
})
.catch(function (error) {
console.log('Error Response: ', error.response);
});
}, (error) => {
console.log('error error!', error) //Display error
});
}
clearAsyncStorage = async () => {
await AsyncStorage.clear();
this.props.navigation.navigate('SignIn');
console.log('Logged Out.')
}
render() {
const { dataSource } = this.state;
return (
<View>
<Text style={{ marginLeft: 20 }}> FreelancerScreen </Text>
<TouchableOpacity onPress={() => this.clearAsyncStorage()}>
<Text style={{ margin: 20, fontSize: 25, fontWeight: 'bold' }}>LogOut</Text>
</TouchableOpacity>
{<FlatList
data={dataSource}
renderItem={({ item }) => {
return (
<View>
<Text style={{ marginLeft: 20 }}>date_start: {item.date_start}</Text>
<Text style={{ marginLeft: 20 }}>total_booked: {item.total_booked}</Text>
</View>
);
}}
/>}
</View>
);
}
};
/*data: {
total_booked: this.state.totalBooked,
date_start: this.state.dateStart,
},*/
Screenshot (React-native):
console screenshot
Screenshot (web Localhost):
Headers Headers 2 Preview Response
Update: I log_message the backend code and got errors such as Trying to get property of non-object and undefined index

Fix Header and Searchbar with Flat list is not working properly

here in my code I am using Fixheader and Searchbar, but I'm trying to put searchbar below header and Header should be fixed .
One more problem is there,After entering anything in search bar then data is coming on FlatList .
Please help me for that , When I'm writing in searchbar or header outside the its generating error .
import React, { Component } from "react";
import {
View,
Text,
TextInput,
FooterTab,
Button,
TouchableOpacity,
ScrollView,
StyleSheet,
ActivityIndicator,
Header,
FlatList
} from "react-native";
import { Icon } from "native-base";
import { createStackNavigator } from "react-navigation";
import { SearchBar } from "react-native-elements";
export default class RenderList extends Component {
static navigationOptions = {
title: "Selected Item",
header: null
};
constructor() {
super();
this.state = {
data: "",
loading: true,
search: "",
searchText: "",
filterByValue: ""
};
}
componentDidMount() {
this.createViewGroup();
}
createViewGroup = async () => {
try {
const response = await fetch("http://example.com",
{
method: "POST",
headers: {
Accept: "application/json",
"Content-Type": "application/json"
},
body: JSON.stringify({
password: "admin",
username: "admin",
viewall: "false",
id: [4],
startlimit: "0",
valuelimit: "10"
})
}
);
const responseJson = await response.json();
const { groupData } = responseJson;
this.setState({
data: groupData,
loading: false
});
} catch (e) {
console.error(e);
}
};
clickedItemText(clickedItem) {
this.props.navigation.navigate("Item", { item: clickedItem });
}
updateSearch = search => {
this.setState({ search });
};
keyExtractor = ({ id }) => id.toString();
keyExtractor = ({ name }) => name.toString();
renderItem = ({ item }) => (
<TouchableOpacity
style={styles.item}
activeOpacity={0.4}
onPress={() => {
this.clickedItemText(item);
}}
>
<Text style={styles.ListText}>Hospital Id {item.id}</Text>
<Text>Hospital Name {item.name}</Text>
</TouchableOpacity>
);
renderSeparator = () => {
return (
<View
style={{
height: 1,
width: "86%",
backgroundColor: "#CED0CE"
}}
/>
);
};
onSearchInputChange = text => {
const filterByValue = this.state.data.filter(x =>
x.name.toLowerCase().includes(text.toLowerCase())
);
this.setState({
searchText: text,
filterByValue
});
};
Render_FlatList_Sticky_header = () => {
var Sticky_header_View = (
<View style={styles.header_style}>
<Text style={{ textAlign: "center", color: "#000000", fontSize: 22 }}>
{" "}
FlatList Sticky Header{" "}
</Text>
</View>
);
return Sticky_header_View;
};
render() {
const { loading, data, filterByValue } = this.state;
return (
<ScrollView>
<View style={styles.container1}>
<SearchBar
lightTheme
onChangeText={this.onSearchInputChange}
value={this.state.searchText}
//onClearText={someMethod}
icon={{ type: "font-awesome", name: "search" }}
placeholder="Type Here..."
/>
{/* <TextInput style={styles.Searchbar}
onChangeText={this.onSearchInputChange}
value={this.state.searchText}
/> */}
{this.state.loading ? (
<ActivityIndicator size="large" />
) : (
<FlatList
renderItem={this.renderItem}
keyExtractor={this.keyExtractor}
ItemSeparatorComponent={this.renderSeparator}
data={filterByValue}
ListHeaderComponent={this.Render_FlatList_Sticky_header}
stickyHeaderIndices={[0]}
// ListHeaderComponent={this.render_FlatList_header}
/>
)}
</View>
</ScrollView>
);
}
}

React Native NetInfo 'connectionChange' event not fired

I have two PoCs I'm working on. 1)RNRestAPI. 2)RNNavigate.
In RNRestAPI index.android.js and index.ios.js both looks like this;
import React, { Component } from 'react';
import {
AppRegistry,
View
} from 'react-native';
import Login from './app/screens/Login/Login';
import About from './app/screens/About/About';
export default class RNRestAPI extends Component {
render() {
return (
<View style={{flex:1}}>
<Login />
</View>
);
}
}
AppRegistry.registerComponent('RNRestAPI', () => RNRestAPI);
Login.js is like this;
import React, { Component } from 'react';
import {
AppRegistry,
View,
TextInput,
StyleSheet,
Button,
Text,
Alert,
TouchableHighlight,
Platform,
Image,
NetInfo,
ProgressBarAndroid,
ProgressViewIOS
} from 'react-native';
import I18n from '../../resources/strings/i18n';
import Colors from '../../resources/styles/colors';
import Dimensions from '../../resources/styles/dimensions';
import Styles from '../../resources/styles/styles';
import Config from '../../config';
export default class Login extends Component {
constructor() {
super();
this.state = {
username:'',
password:'',
buttonLoginDisabled:false,
isConnected:false
}
// I18n.locale = 'en';
}
componentWillMount() {
NetInfo.addEventListener(
'connectionChange',
this.handleConnectivityChange.bind(this)
);
}
componentWillUnmount() {
NetInfo.removeEventListener('connectionChange', handleConnectivityChange);
}
handleConnectivityChange(connectionInfo) {
console.log('First change, type: ' + connectionInfo.type + ', effectiveType: ' + connectionInfo.effectiveType);
if(connectionInfo.type === 'none') {
this.setState({
isConnected:false,
buttonLoginDisabled:true
});
} else {
this.setState({
isConnected:true,
buttonLoginDisabled:false
});
}
}
onLoginClicked() {
var valid = this.validateLoginForm();
if(valid === true) {
this.setState({
buttonLoginDisabled:true
});
this.makeLoginRequest();
} else {
Alert.alert(I18n.t('dialogLoginInvalidTitle'), I18n.t('dialogLoginInvalidMessage'));
}
}
validateLoginForm() {
if(this.state.username === '') {
return false;
}
if(this.state.password === '') {
return false;
}
return true;
}
makeLoginRequest() {
fetch('http://webapitest', {
method: 'POST',
headers: {
'Accept': 'application/json',
'Content-Type': 'application/json',
'MobilePlatformId': Config.MobilePlatformId,
'ApplicationId': Config.ApplicationId,
'Version': '1.9.6'
},
body: JSON.stringify({
Username: this.state.username,
Password: this.state.password
})
})
.then((response) => response.json())
.then((responseJson) => {
console.log(responseJson);
if(responseJson.Token !== null) {
console.log('login successful');
} else {
this.setState({
buttonLoginDisabled:false
});
Alert.alert(I18n.t('dialogInvalidLoginTitle'), I18n.t('dialogInvalidLoginMesage'));
}
})
.catch((error) => {
console.log(eror);
this.setState({
buttonLoginDisabled:false
});
})
}
setUsername(value) {
this.setState({
username:value
});
}
setPassword(value) {
this.setState({
password:value
});
}
onMoreClicked() {
Alert.alert(I18n.t('dialogLearnMoreTitle'), I18n.t('dialogLearnMoreMesage'));
}
getLoginButtonStyle() {
if(this.state.buttonLoginDisabled) {
return styles.buttonLoginDisabled;
} else {
return styles.buttonLogin;
}
}
render() {
return (
<View style={styles.container}>
<View>
<Image source={require('../../resources/images/facilit_logo_welcome.png')}
style={{width:266, height:50, resizeMode:Image.resizeMode.cover}} />
</View>
<View style={styles.wrapperLoginInput}>
<TextInput
keyboardType='default'
placeholder={I18n.t('username')}
returnKeyType='next'
onChangeText={(value) => this.setUsername(value)}
style={Styles.primaryTextInput} />
<TextInput secureTextEntry={true}
placeholder={I18n.t('password')}
onChangeText={(value) => this.setPassword(value)}
style={Styles.primaryTextInput} />
<TouchableHighlight onPress={this.onLoginClicked.bind(this)}
style={{marginTop:(Platform.OS === 'ios') ? 10 : 30}}
underlayColor='#00000000'
disabled={this.state.buttonLoginDisabled}>
<View style={this.getLoginButtonStyle()}>
<Text style={styles.buttonLoginText}>{I18n.t('login')}</Text>
</View>
</TouchableHighlight>
<View style={styles.wrapperLearnMoreLink}>
<TouchableHighlight onPress={this.onMoreClicked.bind(this)}
underlayColor='#00000000'>
<Text style={styles.learnMoreLink}>{I18n.t('learnMore')}</Text>
</TouchableHighlight>
</View>
</View>
</View>
);
}
}
const styles = StyleSheet.create({
container: {
flex:1,
backgroundColor:Colors.primaryBlue,
justifyContent:'center',
alignItems:'center'
},
wrapperLoginInput: {
width:300,
marginTop:100
},
buttonLogin: {
backgroundColor:Colors.primaryYellow,
alignItems:'center',
height:Dimensions.primaryButtonHeight,
justifyContent:'center',
borderRadius:Dimensions.primaryButtonBorderRadius,
borderWidth:Dimensions.primaryButtonBorderWidth,
borderColor:Colors.primaryButtonBorderColor,
},
buttonLoginDisabled: {
backgroundColor:Colors.primaryButtonDisabledGray,
alignItems:'center',
height:Dimensions.primaryButtonHeight,
justifyContent:'center',
borderRadius:Dimensions.primaryButtonBorderRadius,
borderWidth:Dimensions.primaryButtonBorderWidth,
borderColor:Dimensions.primaryButtonBorderColor,
},
buttonLoginText: {
fontSize:Dimensions.primaryButtonFontSize,
color:Colors.primaryButtonFontColor
},
wrapperLearnMoreLink: {
alignItems:'center',
marginTop:150,
},
learnMoreLink: {
color:Colors.secondaryTextColor,
textDecorationLine:'underline'
}
});
AppRegistry.registerComponent('Login', () => Login);
The important bits are componentWillMount() and handleConnectivityChange(connectionInfo). They work as expected and my code handles online/offline scenarios.
The second PoC(RNNavigate) is basically a copy of RNRestAPI but with the inclusion of react-navigation https://reactnavigation.org/. I'm basically trying to create the navigation for my app after the user logs in successfully into my app. So accordingly I have done the following modification to my code.
1) Create App.js
import React, { Component } from 'react';
import {
AppRegistry,
View
} from 'react-native';
import Login from './app/screens/Login/Login';
import About from './app/screens/About/About';
import FacilitySearch from './app/screens/FacilitySearch/FacilitySearch';
import { StackNavigator } from 'react-navigation';
export default class RNNavigate extends Component {
render() {
return (
<View style={{flex : 1}}>
<RNNavigateApp />
</View>
);
}
}
const RNNavigateApp = StackNavigator({
Login : {
screen : Login,
navigationOptions : ({navigation}) => ({
header : null
})
},
About : { screen : About },
FacilitySearch : {
screen : FacilitySearch,
navigationOptions : ({
headerLeft : null
})
}
});
AppRegistry.registerComponent('RNNavigate', () => RNNavigate);
2) Modify index.android.js and index.ios.js to;
import './App.js';
Login.js is untouched. But the connectionChange event is no longer fired. Any expert help is much appreciated to guide me figuring out as to why it's no longer fired or educate me on if I have done something wrong in terms of using React Navigate.
For me, the event was not fired because I didn't restart my react-native server after adding <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" /> in the AndroidManifest.xml.
Kill your server and restart it after then it should fire.

Getting an error that's coming out of no where in React Native app

I really can't see how I'm getting undefined is not object (evaluating 'ReactPropTypes.string) error in my iOS simulator. My code in the WebStorm IDE isn't throw me any errors. I've tried deleting my node_modules folder and then running npm install in Terminal because that usually solves most problems, but not in this case.
Here's Secured.js:
import React, { Component } from 'react';
import { connect } from 'react-redux';
import { ScrollView, Text, View, Button } from 'react-native';
import { logout } from '../redux/actions/auth';
import DropdownMenu from 'react-native-dropdown-menu';
import Icon from './Icon';
class Secured extends Component {
render() {
var data = [["Choice 1"], ["Choice 2"], ["Choice 3"], ["Choice 4"]];
return(
<ScrollView style={{padding: 20}}>
<Icon/>
<Text style={{fontSize: 27}}>
{`Welcome ${this.props.username}`}
</Text>
<View style={{flex: 1}}>
<DropdownMenu style={{flex: 1}}
bgColor={"purple"} //the background color of the head, default is grey
tintColor={"white"} //the text color of the head, default is white
selectItemColor={"orange"} //the text color of the selected item, default is red
data={data}
maxHeight={410} // the max height of the menu
handler={(selection, row) => alert(data[selection][row])} >
<View style={{flex: 1, alignItems: 'center', justifyContent: 'center'}} >
</View>
</DropdownMenu>
</View>
<View style={{margin: 20}}/>
<Button onPress={(e) => this.userLogout(e)} title="Logout"/>
</ScrollView>
);
}
}
const mapStateToProps = (state, ownProps) => {
return {
username: state.auth.username
};
}
const mapDispatchToProps = (dispatch) => {
return {
onLogout: () => { dispatch(logout()); }
}
}
export default connect(mapStateToProps, mapDispatchToProps)(Secured);
Here's Login.js:
import React, { Component } from 'react';
import { connect } from 'react-redux';
import { ScrollView, Text, TextInput, View, Button, StyleSheet } from 'react-native';
import { login } from '../redux/actions/auth';
import {AuthenticationDetails, CognitoUser, CognitoUserAttribute, CognitoUserPool} from '../lib/aws-cognito-identity';
const awsCognitoSettings = {
UserPoolId: 'something',
ClientId: 'something'
};
class Login extends Component {
constructor (props) {
super(props);
this.state = {
page: 'Login',
username: '',
password: ''
};
}
get alt () { return (this.state.page === 'Login') ? 'SignUp' : 'Login'; }
handleClick (e) {
e.preventDefault();
const userPool = new CognitoUserPool(awsCognitoSettings);
// Sign up
if (this.state.page === 'SignUp') {
const attributeList = [
new CognitoUserAttribute({ Name: 'email', Value: this.state.username })
];
userPool.signUp(
this.state.username,
this.state.password,
attributeList,
null,
(err, result) => {
if (err) {
alert(err);
this.setState({ username: '', password: '' });
return;
}
console.log(`result = ${JSON.stringify(result)}`);
this.props.onLogin(this.state.username, this.state.password);
}
);
} else {
const authDetails = new AuthenticationDetails({
Username: this.state.username,
Password: this.state.password
});
const cognitoUser = new CognitoUser({
Username: this.state.username,
Pool: userPool
});
cognitoUser.authenticateUser(authDetails, {
onSuccess: (result) => {
console.log(`access token = ${result.getAccessToken().getJwtToken()}`);
this.props.onLogin(this.state.username, this.state.password);
},
onFailure: (err) => {
alert(err);
this.setState({ username: '', password: '' });
return;
}
});
}
}
togglePage (e) {
this.setState({ page: this.alt });
e.preventDefault();
}
render() {
return (
<ScrollView style={{padding: 20}}>
{/*<Text style={styles.title}>Welcome!</Text>*/}
<TextInput
style={styles.pw}
placeholder=' Email Address'
autoCapitalize='none'
autoCorrect={false}
autoFocus={true}
keyboardType='email-address'
value={this.state.username}
onChangeText={(text) => this.setState({ username: text })} />
<TextInput
style={styles.pw}
placeholder=' Password'
autoCapitalize='none'
autoCorrect={false}
secureTextEntry={true}
value={this.state.password}
onChangeText={(text) => this.setState({ password: text })} />
<View style={{margin: 7}}/>
<Button onPress={(e) => this.handleClick(e)} title={this.state.page}/>
<View style={{margin: 7, flexDirection: 'row', justifyContent: 'center'}}>
<Text onPress={(e) => this.togglePage(e)} style={styles.buttons}>
{this.alt}
</Text>
</View>
</ScrollView>
);
}
}
const styles = StyleSheet.create({
title: {
fontSize: 27,
textAlign: 'center'
},
icon: {
position: 'absolute'
},
pw: {
paddingRight: 90,
justifyContent: 'flex-end',
marginBottom: 20,
backgroundColor: '#9b42f4',
height: 40,
borderWidth: 1,
borderRadius: 5
},
buttons: {
fontFamily: 'AvenirNext-Heavy'
}
});
const mapStateToProps = (state, ownProps) => {
return {
isLoggedIn: state.auth.isLoggedIn
};
}
const mapDispatchToProps = (dispatch) => {
return {
onLogin: (username, password) => { dispatch(login(username, password)); }
}
}
export default connect(mapStateToProps, mapDispatchToProps)(Login);
Check this out, this looks like the issue you're having https://github.com/facebook/react-native/issues/14588#issuecomment-309683553
npm install react#16.0.0-alpha.12 solves the problem.

Categories

Resources