Not connecting to Stripe API - javascript

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);
});
},
);

Related

React Native: Possible unhandled promise rejection (id: 0) TypeError: Network request failed

I'm getting the following error: Possible unhandled promise rejection (id:0): Network request failed.
enter image description here
I am trying to convey a review with text and a picture in firebase. In ReviewsScreen.js display and acceptance of data is implemented, in Fire.js processing and sending. I think somewhere in Fire.js the error lies but I have no ideas what the problem is
ReviewsScreen.js
import React, { Component } from 'react';
import {
StyleSheet,
View,
TouchableOpacity,
Text,
SafeAreaView,
Image,
TextInput,
SafeAreaViewBase
} from 'react-native';
import Icon from 'react-native-vector-icons/Ionicons'
import {h, w} from '../../constants'
import Fire from '../../Fire'
import ImagePicker from 'react-native-image-picker';
const options = {
title: 'Select photo',
};
export default class ReviewsScreen extends Component {
state = {
text: '',
image: null
}
pickImage = () => ImagePicker.showImagePicker(options, (response) => {
console.log('Response = ', response);
if (response.didCancel) {
console.log('User cancelled image picker');
} else if (response.error) {
console.log('ImagePicker Error: ', response.error);
} else {
// You can also display the image using data:
// const source = { uri: 'data:image/jpeg;base64,' + response.data };
this.setState({
image: response.uri
});
}
});
handleReview = () => {
Fire.shared.addReview({text: this.state.text.trim(), localUrl: this.state.image}).then(ref => {
this.setState({text: '', image: null})
this.props.navigation.goBack()
}).catch(error => {
alert(error)
})
}
render() {
return (
<SafeAreaView style={styles.container}>
<View style={styles.header}>
<TouchableOpacity onPress={() => this.props.navigation.goBack()}>
<Icon name='md-arrow-back' size={24} color='blue'/>
</TouchableOpacity>
<TouchableOpacity onPress={this.handleReview}>
<Text style={{fontWeight: '500'}}>Добавить</Text>
</TouchableOpacity>
</View>
<View style={styles.inputContainer}>
<Image source={require('./img/avatar.jpg')} style={styles.avatar}/>
<TextInput
autoFocus={true}
multiline={true}
numberOfLines={1}
style={{flex: 1}}
placeholder='Нам важно ваше мнение!'
onChangeText={text => this.setState({ text })}
value={this.state.text}
>
</TextInput>
</View>
<TouchableOpacity style={styles.photo}
onPress={this.pickImage}>
<Icon name='md-camera' size={32} color="#D8D9D8"></Icon>
</TouchableOpacity>
<View syle={{marginHorizontal: 32, marginTop: 32, height: 150}}>
<Image source={{uri: this.state.image}} style={{ marginTop: 32, alignSelf: 'center', width: '50%', height: '50%'}} />
</View>
</SafeAreaView>
)
}
}
Fire.js
import firebaseConfig from './config'
import firebase from 'firebase'
class Fire {
constructor() {
firebase.initializeApp(firebaseConfig);
}
addReview = async ({ text, localUri }) => {
const remoteUri = await this.uploadPhotoAsync(localUri);
return new Promise((res, rej) => {
this.firestore
.collection("reviews")
.add({
text,
uid: this.uid,
timestamp: this.timestamp,
image: remoteUri
})
.then(ref => {
res(ref);
})
.catch(error => {
rej(error)
});
});
};
uploadPhotoAsync = async uri => {
const path = `photos/${this.uid}/${Date.now()}.jpg`;
return new Promise(async (res, rej) => {
const response = await fetch(uri);
const file = await response.blob();
let upload = firebase
.storage()
.ref(path)
.put(file);
upload.on(
"state_changed",
snapshot => {},
err => {
rej(err);
},
async () => {
const url = await upload.snapshot.ref.getDownloadURL();
res(url);
}
);
});
};
get firestore() {
return firebase.firestore();
}
get uid() {
return (firebase.auth().currentUser || {}).uid;
}
get timestamp() {
return Date.now();
}
}
Fire.shared = new Fire();
export default Fire;
You wrote "localUrl" instead of "localUri":
Fire.shared.addReview({text: this.state.text.trim(), localUrl: this.state.image}).then(ref => {

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

React Native AXIOS method GET response.data shows null

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,
},*/

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>
);
}
}

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