Login/Register problem in react native app mobile using laravel backend - javascript

I'm a beginner in react native, I'm struggling into Login/Register functions, in my metro, it doesn't show login successfully just like in my backend, please help me!
This is my backend result.
And this is my code Login.js
In my metro, it shows no results, as It should show success:true or something like that as many tutorials I checked on youtube, thanks in advance.
import React, { useState } from 'react'
import { TouchableOpacity, StyleSheet, View } from 'react-native'
import { Text } from 'react-native-paper'
import Background from '../components/Background'
import Logo from '../components/Logo'
import Header from '../components/Header'
import Button from '../components/Button'
import TextInput from '../components/TextInput'
import BackButton from '../components/BackButton'
import { theme } from '../core/theme'
import { emailValidator } from '../helpers/emailValidator'
import { passwordValidator } from '../helpers/passwordValidator'
export default function login({ navigation }) {
const [email_user, setEmail_user] = useState({ value: '', error: '' })
const onLoginPressed = () => {
const emailError = emailValidator(email_user.value)
const passwordError = passwordValidator(password.value)
if (emailError || passwordError) {
setEmail_user({ ...email_user, error: emailError })
setPassword({ ...password, error: passwordError })
return
}
navigation.reset({
index: 0,
routes: [{ name: 'Home' }],
})
}
const [password, setPassword] = useState("");
const login = () => {
const data = { email_user: email_user, password: password };
axios.post('http://10.0.2.2:8000/api/auth/login', data).then((response) => {
if (response.data.error) {
alert(response.data.error);
} else {
sessionStorage.setItem("accessToken", response.data);
history.push("/");
}
});
};
return (
<Background>
<BackButton goBack={navigation.goBack} />
<Logo />
<Header></Header>
<TextInput
label="Email"
returnKeyType="next"
value={email_user.value}
onChangeText={(text) => setEmail_user({ value: text, error: '' })}
error={!!email_user.error}
errorText={email_user.error}
autoCapitalize="none"
autoCompleteType="email"
textContentType="emailAddress"
keyboardType="email-address"
/>
<TextInput
label="Password"
returnKeyType="done"
value={password.value}
onChangeText={(text) => setPassword({ value: text, error: '' })}
error={!!password.error}
errorText={password.error}
secureTextEntry
/>
<View style={styles.forgotPassword}>
<TouchableOpacity
onPress={() => navigation.navigate('reset')}
>
<Text style={styles.forgot}>Forgot your password?</Text>
</TouchableOpacity>
</View>
<Button mode="contained" onPress={onLoginPressed}>
Login
</Button>
<View style={styles.row}>
<Text>Don’t have an account? </Text>
<TouchableOpacity onPress={() => navigation.replace('register')}>
<Text style={styles.link}>Sign up</Text>
</TouchableOpacity>
</View>
</Background>
)
}
const styles = StyleSheet.create({
forgotPassword: {
width: '100%',
alignItems: 'flex-end',
marginBottom: 24,
},
row: {
flexDirection: 'row',
marginTop: 4,
},
forgot: {
fontSize: 13,
color: theme.colors.secondary,
},
link: {
fontWeight: 'bold',
color: theme.colors.blue,
},
})

Related

Firebase v9 not adding docs

I'm working with Firebase v9. The authentication works fine, but the Firestore does not work me for some reason. I don't even get an error--it just doesn't do anything.
I tried addDocs() but still nothing works.
EDIT: actually , i was using the firebase #9.1.0 i upgraded it to #9.6.7 and it worked perfectly fine ! i had to downgrade from #9.6.8 ( the latest ) to #9.1.0 because of the error ( Can't find variable: IDBIndex ) !
import React, { useLayoutEffect, useState } from "react";
import {
Text,
View,
StyleSheet,
TextInput,
TouchableOpacity,
KeyboardAvoidingView,
Platform,
ScrollView,
Alert,
} from "react-native";
import { AntDesign, Ionicons } from "#expo/vector-icons";
import { doc, setDoc } from "firebase/firestore";
import { db } from "../../firebase/firebaseConfig";
const NewChat = ({ navigation }) => {
const [input, setInput] = useState("");
useLayoutEffect(() => {
navigation.setOptions({
title: "Add a new Chat",
headerBackTitle: "Chats",
});
}, [navigation]);
const AddChat = async () => {
const myDoc = doc(db, "Chats", input);
const docData = {
chatName: input,
};
setDoc(myDoc, docData).then(() => {
navigation.goBack();
});
};
return (
<ScrollView>
<View
style={{
marginTop: 20,
marginHorizontal: 20,
borderColor: "black",
borderWidth: 1,
}}
>
<View style={styles.container}>
<AntDesign
name="wechat"
size={40}
color="black"
style={{ alignSelf: "center" }}
/>
<TextInput
placeholder="Enter a chat name"
value={input}
onChangeText={(text) => {
setInput(text);
}}
style={{ flexGrow: 1, marginLeft: 20 }}
/>
<TouchableOpacity style={{ alignSelf: "center" }} onPress={AddChat}>
<Ionicons name="checkmark-done-circle" size={40} color="black" />
</TouchableOpacity>
</View>
</View>
</ScrollView>
);
};
const styles = StyleSheet.create({
container: {
flexDirection: "row",
backgroundColor: "white",
justifyContent: "center",
height: 60,
},
});
export default NewChat;
The function setDoc() asynchronously returns a promise which means all you're missing is the await keyword before you call the function.
const AddChat = async () => {
const myDoc = doc(db, "Chats", input);
const docData = {
chatName: input,
};
await setDoc(myDoc, docData).then(() => {
navigation.goBack();
});
};
Edit: I think I see the real problem, It has to do with the v9 document reference. Try using collection() within the document reference.
const AddChat = async () => {
const myDoc = doc(collection(db, "Chats"), input);
const docData = {
chatName: input,
};
await setDoc(myDoc, docData).then(() => {
navigation.goBack();
});
};

React Navigation and React Context

In our App we use a tab navigation and a stack navigation for each tab. We want an array of devices where we could add and delete devices. The array should be available on every tab.
This is our provider
import React from 'react'
const DevicesContext = React.createContext('')
export default DevicesContext
This is our app.js
import React, {useState} from 'react';
import uuid from 'react-native-uuid';
import { NavigationContainer } from '#react-navigation/native';
import { createMaterialBottomTabNavigator } from '#react-navigation/material-bottom-tabs';
import { MaterialCommunityIcons } from '#expo/vector-icons';
import { Feather } from '#expo/vector-icons';
import { MaterialIcons } from '#expo/vector-icons';
import HomeStackScreen from "./components/home/HomeStackScreen";
import ConnectStackScreen from "./components/connect/ConnectStackScreen";
import SettingsStackScreen from "./components/settings/SettingsStackScreen";
import DevicesContext from "./components/context/DevicesContext";
const Tab = createMaterialBottomTabNavigator();
const deleteItem = (id) => {
setDevices(prevDevice => {
return prevDevice.filter(device => device.id != id)
})
console.log(devices)
}
const addItem = (device) => {
setDevices(prevDevices => {
return [{id: uuid.v4(), name:device}, ...prevDevices];
})
}
function MyTabs() {
return (
<Tab.Navigator
initialRouteName="Home"
activeColor="#E4E4E4"
inactiveColor="#000000"
shifting={true}
labelStyle={{ fontSize: 12 }}
barStyle={{ backgroundColor: '#8DFFBB' }}
>
<Tab.Screen
name="Devices"
component={ConnectStackScreen}
options={{
tabBarLabel: 'Geräte',
tabBarIcon: ({ color }) => (
<MaterialIcons name="devices" size={24} color={color} />
),
}}
/>
<Tab.Screen
name="Home"
component={HomeStackScreen}
options={{
tabBarLabel: 'Home',
tabBarIcon: ({ color }) => (
<MaterialCommunityIcons name="home" color={color} size={26} />
),
}}
/>
<Tab.Screen
name="Settings"
component={SettingsStackScreen}
options={{
tabBarLabel: 'Einstellungen',
tabBarIcon: ({ color }) => (
<Feather name="settings" size={24} color={color} />
),
}}
/>
</Tab.Navigator>
);
}
export default function App() {
const [devices, setDevices] = useState([
{id: uuid.v4(), name: 'thing 1', ip: 5},
{id: uuid.v4(), name: 'thing 2', ip: 2},
{id: uuid.v4(), name: 'thing 3', ip: 6},
{id: uuid.v4(), name: 'thing 4', ip: 10},
])
return (
<DevicesContext.Provider value={devices}>
<NavigationContainer>
<MyTabs />
</NavigationContainer>
</DevicesContext.Provider>
);
}
this is our connect screen where we can add devices
import React, {useContext, useState} from 'react';
import {Text, View, Button, FlatList, StyleSheet, TouchableOpacity, Image} from 'react-native';
import uuid from 'react-native-uuid';
import ListItem from "../shared/ListItem";
import AddItem from "../shared/AddItem";
import DevicesContext from "../context/DevicesContext";
function ConnectScreen( {navigation}) {
const [devices, setDevices] = useState(useContext(DevicesContext));
const deleteItem = (id) => {
setDevices(prevDevice => {
return prevDevice.filter(device => device.id != id)
})
console.log(devices)
}
const addItem = (device) => {
setDevices(prevDevices => {
return [{id: uuid.v4(), name:device}, ...prevDevices];
})
}
return (
<View style={{padding: 10, flex: 1, justifyContent: 'center'}}>
<View style={styles.AddNormal}>
<AddItem addItem={addItem}></AddItem>
<FlatList style={styles.List} data={devices} renderItem={({item}) => (
<ListItem item={item} deleteItem={deleteItem}></ListItem>
)}/>
</View>
<View style={styles.AddQr}>
<Image source={require('../../img/qr-code-url.png')} style={{ width: 150, height: 150, marginBottom: 10 }} />
<Text style={{ textAlign: 'center', marginBottom: 10 }}>Du kannst außerdem ein Gerät durch das scannen eines Qr-Code hinzufügen</Text>
<TouchableOpacity onPress={() => navigation.navigate('QrCode')}style={styles.btn}>
<Text style={styles.btnText}>Qr-Code scannen</Text>
</TouchableOpacity>
</View>
</View>
);
}
const styles = StyleSheet.create({
List: {
backgroundColor: '#E4E4E4',
},
AddNormal: {
padding: 10, flex: 1,
},
AddQr: {
backgroundColor: '#E4E4E4',
padding: 30,
flex: 1,
marginTop: 20,
marginBottom: 20,
alignItems: 'center'
},
btn: {
backgroundColor: '#8DFFBB',
padding: 9,
margin: 10,
},
btnText: {
color: '#000',
fontSize: 20,
textAlign: 'center',
}
});
export default ConnectScreen;
and this is our main screen
import React, {useState, useContext, useEffect} from 'react';
import {Button, FlatList, SafeAreaView, StatusBar, StyleSheet, Text, TouchableOpacity, View} from "react-native";
import {ServerOnOffSwitch, SendMessage} from "./network";
import DevicesContext from "../context/DevicesContext";
const Item = ({ item, onPress, backgroundColor, textColor }) => (
<TouchableOpacity onPress={onPress} style={[styles.item, backgroundColor]}>
<Text style={[styles.title, textColor]}>{item.name}</Text>
</TouchableOpacity>
);
function HomeScreen (){
const [devices, setDevices] = useState(useContext(DevicesContext));
const deleteItem = (id) => {
setDevices(prevDevice => {
return prevDevice.filter(device => device.id != id)
})
}
const [selectedId, setSelectedId] = useState(null);
const renderItem = ({ item }) => {
const backgroundColor = item.id === selectedId ? "#b5b5b5" : "#ededed";
const color = item.id === selectedId ? 'white' : 'black';
return (
<Item
item={item}
onPress={() => setSelectedId(item.id)}
backgroundColor={{ backgroundColor }}
textColor={{ color }}
/>
);
};
return (
<View style={{padding: 10, flex: 1, justifyContent: 'center'}}>
<View style={{padding: 10, flex: 1}}>
<Text style={styles.DeviceHeader}>Gerät auswählen</Text>
<FlatList
data={devices}
renderItem={renderItem}
keyExtractor={(item) => item.id}
extraData={selectedId}
/>
</View>
<View style={{padding: 10, flex: 1, justifyContent: 'center', alignItems: 'center'}}>
<SendMessage item={selectedId}></SendMessage>
<ServerOnOffSwitch></ServerOnOffSwitch>
</View>
</View>
);
}
const styles = StyleSheet.create({
DeviceHeader: {
fontSize: 22,
paddingBottom: 10,
},
item: {
padding: 10,
backgroundColor: '#f8f8f8',
borderBottomWidth: 1,
borderColor: '#eee',
},
title: {
fontSize: 18,
},
});
export default HomeScreen;
If we add devices in our Connect screen they are getting updated there but not on the homescreen.
Thanks for your help:)
to update context from nested component you must pass the methode setDevices tha will update it.
to pass it do the following steps :
your context shoud be
import React from 'react'
const DevicesContext = React.createContext({
devices: [],
setDevices: () => {}, //methode will update context value
})
export default DevicesContext
App.js should be
//define state
const [devices, setDevices] = React.useState([])
//define constexValue
//we will pass `devices` and also `setDevices` that will update it.
const DevicesContextValue = React.useMemo(() => ({ devices, setDevices}), [devices]);
return (
<DevicesContext.Provider value={DevicesContextValue}>
...
</DevicesContext.Provider>
);
ConnectScreen.js should be
function ConnectScreen(){
const {devices, setDevices} = useContext(DevicesContext);
//call setDevices will update context
....
}
HomeScreen.js should be
function HomeScreen (){
const {devices, setDevices} = useContext(DevicesContext);
//use devices from context in your flatlist and when the context update the result will show in flatlist
....
}

App crashes when entering in screen React Native

I'm making a mobile app and then suddenly when I enter this Screen the whole app crashes. It was working before but, after I changed some style, it gave me some errors about too much Call Stack but stopped saying that and just crashes. I really don't know what's causing this. I tried to see if there was on the UseEffect() I think there is nothing there causing this.
import React, { useEffect, useState, useContext} from "react";
import {
View,
Text,
StatusBar,
TouchableOpacity,
ScrollView,
AsyncStorage,
Dimensions,
Image,
Alert,
} from "react-native";
import PlusImage from "../../../../assets/add_circle-24px.png";
import mainContext from "../../../services/contexts/mainContext";
import listContext from "../../../services/contexts/listContext";
import taskContext from "../../../services/contexts/taskContext";
import { MaterialIcons } from "#expo/vector-icons";
import styles from "./styles";
import TaskItem from "../../utils/TaskItem";
import Animated from "react-native-reanimated";
import { FlatList } from "react-native-gesture-handler";
export default function List({ route, navigation }) {
const {
clean,
getTasksList,
edited,
toogleEdited,
deleteList,
doneTasks,
todoTasks,
} = useContext(listContext);
const { taskEdited, idtask, deleteTask } = useContext(taskContext);
const [listName, setListName] = useState("");
const [screenTasks, setScreenTasks] = useState([{}]);
const [done, setDone] = useState(false);
const screenHeight = Math.round(Dimensions.get("window").height);
async function getListName() {
setListName(await AsyncStorage.getItem("listName"));
}
async function asyncGetTasks() {
await getTasksList();
}
useEffect(() => {
if (listName) getListName();
asyncGetTasks();
setScreenTasks(done ? doneTasks : todoTasks);
if (idtask) {
navigation.navigate("Task");
}
}, [edited, taskEdited, idtask, done]);
return (
<View style={styles.container}>
<StatusBar hidden />
<View style={styles.buttonsContainer}>
<TouchableOpacity
onPress={() => {
navigation.goBack();
clean();
}}
>
<MaterialIcons name="arrow-back" size={32} />
</TouchableOpacity>
<TouchableOpacity
onPress={() => {
Alert.alert(
"Are you sure you want to delete this list?",
"",
[
{
text: "Cancel",
style: "cancel",
},
{
text: "OK",
onPress: () => {
deleteList();
clean();
navigation.goBack();
},
},
],
{ cancelable: true }
);
}}
>
<MaterialIcons name="delete" size={32} color="#bc0000" />
</TouchableOpacity>
</View>
<View style={styles.titleContent}>
<Text style={styles.titleText}>{listName}</Text>
</View>
<View style={styles.midButtonsContainer}>
<View
style={{
opacity: 1,
backgroundColor: done ? null : "#dddddd",
borderRadius: 7,
padding: 8,
opacity: 1,
}}
>
<TouchableOpacity
onPress={() => {
setDone(false);
toogleEdited();
}}
>
<Text>To do</Text>
</TouchableOpacity>
</View>
<View
style={{
opacity: 1,
backgroundColor: done ? "#dddddd" : null,
borderRadius: 7,
padding: 8,
opacity: 1,
}}
>
<TouchableOpacity
onPress={() => {
setDone(true);
toogleEdited();
}}
>
<Text style={styles.doneButton}>Done</Text>
</TouchableOpacity>
</View>
</View>
{screenTasks.length > 0 ? (
<FlatList
data={screenTasks}
renderItem={(item, index) => {
return (
<TaskItem
OnSwipeRight={() => deleteTask(item.item._id)}
{...{ item }}
/>
);
}}
/>
) : (
<View style={styles.emptyContent}>
<Text style={styles.emptyText}>This list don't have tasks yet</Text>
</View>
)}
<TouchableOpacity
style={{
position: "absolute",
top: screenHeight - 120,
right: 28,
flexDirection: "row",
width: 50,
alignSelf: "flex-end",
}}
onPress={() => {
navigation.navigate("NewTask");
}}
>
<Image source={PlusImage} />
</TouchableOpacity>
</View>
);
}
Have you tried to import it from the react lib?
import React, { useEffect } from 'react';
I don't see it in your import above.

How to get params in other App Container - React Navigation?

I want to use the params I passed to Profile Screen and he is in a separate App Container,
And I create TopTabs and put it in a specific AppContainer because I don't have any way to use it in a one AppContainer so how I Get these Params from another AppContainer?
So My Code here's
First thing, now I'm in the Map Screen and want to navigate to profile screen and pass some params like this
this.props.navigation.navigate('ProviderProfile', {
providerId: marker.id,
providerName: marker.name,
providerService: marker.service,
gKey: marker.gKey,
token: marker.token._55,
region: region
}
And here is Profile Screen, Contain let's say Card and TobTabs "I wrap it in a separate AppContainer"
and want to use params I passed in these TopTabs "every single tab" so how to handle these OR pass these params to every single Tab?
ProviderProfile.js
import React, { Component } from "react";
import Icon from "react-native-vector-icons/Ionicons";
import firebase from "react-native-firebase";
import { createAppContainer } from "react-navigation";
import { NavTabs } from "./ProviderTabs/NabTabs";
import { View, Text, StyleSheet, TouchableOpacity, Image } from "react-native";
console.disableYellowBox = true;
class ProviderProfile extends Component {
static navigationOptions = ({ navigation }) => {
const { state } = navigation;
return {
title: ` ${state.params.providerName}` || "profile"
};
};
constructor(props) {
super(props);
this.state = {
providerId: this.props.navigation.getParam("providerId"),
providerService: this.props.navigation.getParam("providerService"),
providerName: this.props.navigation.getParam("providerName"),
gKey: this.props.navigation.getParam("gKey"),
token: this.props.navigation.getParam("token"),
region: this.props.navigation.getParam("region"),
fav: false
};
}
_addToFavorite = () => {
const { providerName, providerService, providerId, fav } = this.state;
const currentUser = firebase.auth().currentUser.uid;
this.setState({ fav: !fav });
const ref = firebase
.database()
.ref(`favorites/${currentUser}/${providerId}`);
if (!fav) {
ref
.set({
ProviderId: providerId,
providerName: providerName,
providerService: providerService
})
.then(() => alert("Great, Added to your favorite list"));
} else {
ref.remove();
}
};
render() {
const {
providerName,
providerService,
providerId,
fav,
gKey,
region,
token
} = this.state;
return (
<View style={styles.container}>
{/* <Text>{gKey}</Text> */}
<Image
resizeMode="contain"
source={require("../assets/marker.png")}
/>
<View>
<View>
<Icon
name={`ios-heart${fav ? "" : "-empty"}`}
size={35}
color="#f00"
onPress={this._addToFavorite}
/>
</View>
<Text>
<Icon name="ios-star" size={20} color="#f2ba13" />
<Icon name="ios-star" size={20} color="#f2ba13" />
<Icon name="ios-star" size={20} color="#f2ba13" />
<Icon name="ios-star-half" size={20} color="#f2ba13" />
<Icon name="ios-star-outline" size={20} color="#f2ba13" />
</Text>
<Text style={{ fontSize: 19, color: "#000", padding: 5 }}>
{providerName}
</Text>
<Text>
Service: <Text>{providerService}</Text>
</Text>
<View style={{ flexDirection: "row", marginTop: 10 }}>
<TouchableOpacity
onPress={() => alert("Message")}
>
<Text>
Message
</Text>
</TouchableOpacity>
<TouchableOpacity
onPress={() =>
this.props.navigation.navigate("Order", {
providerName,
providerId,
providerService,
gKey,
token,
region
})
}
>
<Text
>
Send Order
</Text>
</TouchableOpacity>
</View>
</View>
<Roots /> // Here's Tabs
</View>
);
}
}
const Roots = createAppContainer(NavTabs);
export default ProviderProfile;
And Here is a Tabs Screen "NavTabs"
import {
createMaterialTopTabNavigator,
} from "react-navigation";
import AboutScreen from "./About";
import GalaryScreen from "./Galary";
import ReviewsScreen from "./Reviews";
export const NavTabs = createMaterialTopTabNavigator(
{
About: { screen: AboutScreen },
Galaty: { screen: GalaryScreen },
Reviews: { screen: ReviewsScreen }
},
{
tabBarOptions: {
activeTintColor: "#fff",
inactiveTintColor: "#ddd",
tabStyle: {
justifyContent: "center"
},
indicatorStyle: {
backgroundColor: "#fcc11e"
},
style: {
backgroundColor: "#347ed8"
}
}
}
);
As you see, I want to use the username in Tab "About"
or other Tabs
Send params:
this.props.navigation.navigate('RouteName', { /* params go here */ })
Get params:
this.props.navigation.getParam(paramName, defaultValue)
Example:
this.props.navigation.navigate('NameListScreen', { names:["John","Mary"] })
let params = this.props.navigation.getParam(names, [])
I haven't use React Navigation myself but in their documentation say you can pass props to App Containers, so as you have defined the state with the props from the MapScreen you should probably pass them as props where you have defined your NavTabs Component as <Roots />
Also, there is another alternative to want to achieve as they present in here and it will be done in a redux way.

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