Navigation from one page to another in react native using navigate - reactjs

I am currently learning react native. I want to navigate from one screen to another using navigate() function. Navigate function is placed inside a fetch() function, so after i get the response from the server, I should be redirected to the next page. But currently i an having problem as the navigation code is not working if i put inside the fetch(). If i remove the code and place it outside the fetch then it is working.
Below is my written code (StepOne):
import React, { Component } from 'react';
import { Text, View, StyleSheet, ImageBackground, TextInput, TouchableOpacity, Alert } from 'react-native';
import { Tile } from 'react-native-elements';
export default class StepOne extends Component {
static navigationOptions = {
header: null
};
constructor(props) {
super(props);
this.state = {
userEmail : '',
userPhone : ''
}
}
moveToStepTwo = () => {
const {userEmail} = this.state;
const {userPhone} = this.state;
if(userEmail == '' || userPhone == '') {
Alert.alert('Warning' , 'Please Insert All the Required Details !!!!');
} else {
let url = 'registerProcessGetEmailValidity.jsp?';
let param_one = 'user_email='+userEmail;
let seperator_param = '&';
let full_url = '';
full_url = url + param_one;
let header = {
'Accept': 'application/json',
'Content-Type': 'application/json'
};
fetch( full_url, {
method: 'GET',
headers: header,
})
.then(function(response) {
return response.json();
})
.then(function(myJson) {
console.log(myJson);
if(myJson.message == 'No User') {
this.props.navigation.navigate('StepTwo', { userEmail: this.state.userEmail , userPhone: this.state.userPhone } );
} else if (myJson.message == 'Got User') {
Alert.alert('Warning' , 'Email is registered, Choose different email !!!!');
}
});
}
}
render() {
const { navigate } = this.props.navigation;
return (
<View style={styles.container}>
<ImageBackground source={require('../../img/background1.jpg')} style={styles.backgroundImage}>
<View style={styles.content}>
<Text style={styles.logo}> -- STEP 1 -- </Text>
<View style={styles.inputContainer}>
<TextInput
underlineColorAndroid='transparent' style={styles.input} placeholder='ENTER EMAIL'
onChangeText = {userEmail => this.setState({userEmail})} >
</TextInput>
<TextInput
underlineColorAndroid='transparent' keyboardType = {'numeric'} maxLength={12}
style={styles.input} placeholder='ENTER PHONE NUMBER' onChangeText = {userPhone => this.setState({userPhone})} >
</TextInput>
</View>
<View style={styles.buttonHolder}>
<TouchableOpacity style={styles.buttonContainer} onPress={ this.moveToStepTwo }>
<Text style={styles.buttonText}>NEXT</Text>
</TouchableOpacity>
<TouchableOpacity style={styles.buttonContainer} onPress={ ()=> navigate('Home') } >
<Text style={styles.buttonText}>CANCEL</Text>
</TouchableOpacity>
</View>
</View>
</ImageBackground>
</View>
);
}
}
When I navigate to the 'StepTwo' screen after the fetch call, there is no response. I can't navigate to the next screen. It is like the navigate call inside the fetch is not working. Can anyone help me to solve this problem ?
And one more thing. Is the any fault in my code ? Since i am new to react native, i have no idea what I am writing is correct or not. Maybe regarding the this. something element.
I give another example (App.js):
import React from 'react';
import { StyleSheet, Text, View, TouchableOpacity } from 'react-native';
import { StackNavigator } from 'react-navigation';
import Expo from 'expo';
import HomeScreen from './app/screens/HomeScreen';
import LoginScreen from './app/screens/LoginScreen';
import RegisterScreen from './app/screens/RegisterScreen';
const NavigationApp = StackNavigator({
Home: { screen: HomeScreen },
Login: { screen: LoginScreen },
Register: { screen: RegisterScreen },
});
export default class App extends React.Component {
render() {
return (
<NavigationApp />
);
}
}
Then Login file (Login.js)
import React, { Component } from 'react';
import { Text, View, StyleSheet, ImageBackground, TextInput, TouchableOpacity, Alert } from 'react-native';
import { FormLabel, FormInput } from 'react-native-elements'
export default class Login extends Component {
static navigationOptions = {
header: null
};
constructor(props) {
super(props);
this.state = {
userName : '',
userPass : ''
}
}
login = () => {
const {userName} = this.state;
const {userPass} = this.state;
if(userName == '' || userPass == '') {
Alert.alert('Warning' , 'Please Insert All the Required Details !!!!');
} else {
let url = 'loginProcessGetUserDetails.jsp?';
let param_one = 'user_name='+userName;
let param_two = 'user_pass='+userPass;
let param_three = 'user_group=JOMLOKA';
let seperator_param = '&';
let full_url = '';
full_url = url + param_one + seperator_param + param_two + seperator_param + param_three;
let header = {
'Accept': 'application/json',
'Content-Type': 'application/json'
};
fetch( full_url, {
method: 'GET',
headers: header,
})
.then(function(response) {
return response.json();
})
.then(function(myJson) {
console.log(myJson);
if(myJson.message == 'No User') {
Alert.alert('Warning' , 'No User !!!!');
} else if (myJson.message == 'Wrong Password') {
Alert.alert('Warning' , 'Wrong Password !!!!');
} else if (myJson.message == 'Login') {
//Alert.alert('Success' , 'Login !!!!');
const { navigate } = this.props.navigation;
navigate("Register",{ userEmail: this.state.userEmail , userPhone: this.state.userPhone });
}
});
}
}
render() {
const { navigate } = this.props.navigation;
return (
<View style={styles.container}>
<ImageBackground source={require('../img/background1.jpg')} style={styles.backgroundImage}>
<View style={styles.content}>
<Text style={styles.logo}> -- LOGIN DEMO -- </Text>
<View style={styles.inputContainer}>
<TextInput underlineColorAndroid='transparent' style={styles.input} placeholder='ENTER USERNAME' onChangeText = {userName => this.setState({userName})} >
</TextInput>
<TextInput underlineColorAndroid='transparent' secureTextEntry={true} style={styles.input} placeholder='ENTER PASSWORD' onChangeText = {userPass => this.setState({userPass})} >
</TextInput>
</View>
<View style={styles.buttonHolder}>
<TouchableOpacity onPress={this.login} style={styles.buttonContainer}>
<Text style={styles.buttonText}>LOGIN</Text>
</TouchableOpacity>
<TouchableOpacity onPress={ ()=> navigate('Home') } style={styles.buttonContainer}>
<Text style={styles.buttonText}>CANCEL</Text>
</TouchableOpacity>
</View>
</View>
</ImageBackground>
</View>
);
}
}
That is another example with the same problem.

Replace
onPress={ this.moveToStepTwo }
with
onPress={()=> this.moveToStepTwo() }

this.props.navigation.navigate('StepTwo', { userEmail: this.state.userEmail , userPhone: this.state.userPhone } );
Are you sure your this is correct?
If you don't use Arrow Function, you need to do this var _this = this, then _this.props.navigation.navigate('StepTwo', { userEmail: this.state.userEmail , userPhone: this.state.userPhone } );
You can use Arrow functiom in fetch:
fetch(url, options)
.then(response => {
// ...
})
.catch(error => {
// ...
})

I assume that you have installed react-navigation plugin.
Now import your files in the app.js
like below :
import login from './login';
import StepTwo from './StepTwo';
const Nav = StackNavigator({
login : {screen: login},
StepTwo : {screen: StepTwo},
});
export default class FApp extends Component {
render() {
return (
<Nav/>
);
}
}
And in your login file. (Considering your this file as a login file)
if(myJson.message == 'No User') {
const { navigate } = this.props.navigation;
navigate("StepTwo",{ userEmail: this.state.userEmail , userPhone: this.state.userPhone });
} else if (myJson.message == 'Got User') {
Alert.alert('Warning' , 'Email is registered, Choose different email !!!!');
}

Related

set Multiple state Id for custom component in React Native

I have implemented custom inputBox component. So When I am using this component first time then it is working fine and when I am using multiple time in one page then data is prepopulate to next component.
Custom component:
import React, { createRef } from 'react';
import {
View,
TextInput,
Alert,
Text,
StyleSheet
} from "react-native";
class BoxInput extends React.Component {
constructor(props) {
super(props)
this.state = {
digit1: '',
digit2: '',
digit3: '',
...props
}
this.digit1Ref = createRef()
this.digit2Ref = createRef()
this.digit3Ref = createRef()
}
componentDidMount() {
this.digit1Ref.current.focus()
}
componentDidUpdate(prevProps) {
if (this.state.digit1 && this.state.digit2 &&
this.state.digit3
}
saveText(text, key) {
this.setState({ ...this.state, [key]: text }, () => {
if (text) {
key == 'digit1' ? this.digit2Ref.current.focus() : null
key == 'digit2' ? this.digit3Ref.current.focus() : null
key == 'digit3'
}
const boxInputValue = this.state.digit1 + this.state.digit2 + this.state.digit3
this.props.onBoxInput(boxInputValue)
});
}
render() {
return (
<>
<TextInput maxLength={1} keyboardType={'numeric'} ref={this.digit1Ref} style={styles.boxStyle} value={this.state.digit1} onChangeText={(text) => this.saveText(text, 'digit1')} />
<TextInput maxLength={1} keyboardType={'numeric'} ref={this.digit2Ref} style={styles.boxStyle} value={this.state.digit2} onChangeText={(text) => this.saveText(text, 'digit2')} />
<TextInput maxLength={1} keyboardType={'numeric'} ref={this.digit3Ref} style={styles.boxStyle} value={this.state.digit3} onChangeText={(text) => this.saveText(text, 'digit3')} />
</>
)
}
}
const styles = StyleSheet.create({
boxStyle: {
marginTop: 20,
height: 57,
width: 50,
borderRadius: 10,
borderWidth: 1,
borderColor: '#F1F5F9',
backgroundColor: '#F1F5F9',
fontSize: 20,
lineHeight: 40,
paddingHorizontal: 15,
textAlign: 'center'
}
})
export default BoxInput;
import React, { createRef } from 'react';
import styles from './style';
import {
View,
TextInput,
Alert
} from "react-native";
import { connect } from "react-redux";
import * as Animatable from 'react-native-animatable';
import BoxInput from "../../../../md-components/atoms/boxinput"
class MPINScreen extends React.Component {
constructor(props) {
super(props)
this.state = {
confirmMpinEnable: true,
...props
}
this.codes = [{
value: '+91',
}]
}
componentDidUpdate(prevProps) {
if (this.state.mpinValue.split("").length == 3 &&
prevProps.success_msg != this.props.success_msg && this.props.success_msg == 'verified') {
NavigationService.navigate(this.props.navigation, 'MPINVerifyOnboarding')
}
}
handleSubmit = () => {
if (this.state.mpinValue != this.state.confirmMpinValue) {
Alert.alert(
"Error",
"MPIN is not machted",
[
{ text: "OK" }
],
{ cancelable: false }
);
} else {
this.props.verifyMpin({
"mpin": this.state.mpinValue,
phoneNumber: this.props.mobileNumber
})
}
}
mpinConfirmation = () => {
if (this.state.mpinValue.split("").length != 6) {
Alert.alert(
"Error",
"Please insert 6 digit mpin",
[
{ text: "OK" }
],
{ cancelable: false }
);
}else{
this.setState({
confirmMpinEnable: false,
});
}
}
mpinText = (args) => {
this.setState({
mpinValue: args,
});
}
confirmMpinText = (args) => {
this.setState({
confirmMpinValue: args,
});
}
render() {
return (
<>
<HeaderComponent backgroundColor="#E5E5E5" showLeftIcon={true} showRightIcon={false} />
<View style={styles.container}>
<Text style={[styles.textInfo, styles.textTitle]}>We are almost there!</Text>
<View style={styles.imageWrapper}>
<Animatable.View animation="slideInDown" iterationCount={1} style={styles.centerIconWrap}>
<Image style={styles.centerIcon} source={mpin_card} />
</Animatable.View>
</View>
{this.state.confirmMpinEnable ?
<Text style={[styles.textInfo]}>Setup your MPIN</Text> : <Text style={[styles.textInfo]}>Confirm your MPIN</Text>
}
{this.state.confirmMpinEnable ?
<View style={styles.rowWrap}>
<BoxInput id="catFood1" onBoxInput={this.mpinText} />
</View>:
<View style={styles.rowWrap}>
<BoxInput id="catFood2" onBoxInput={this.confirmMpinText} />
</View>
}
<View style={styles.marginBottom}>
<Text style={[styles.mpinNote]}>M-PIN is a short 6-digit PIN that you have to set for</Text>
<Text style={[styles.mpinNote]}>our mandatory Two-Factor Authentication</Text>
</View>
<View style={styles.bottomBtnSyle}>
<View style={styles.multipleBtnStyle}>
<Button onPress={this.handleBack}>{"Back"}</Button>
</View>
{this.state.confirmMpinEnable ?
<View style={styles.multipleBtnStyle}>
<Button onPress={this.mpinConfirmation} >{"Confirm"}</Button>
</View> :
<View style={styles.multipleBtnStyle}>
<Button onPress={this.handleSubmit} >{"Save & Continue"}</Button>
</View>
}
</View>
</View>
</>
)
}
}
export default connect(mapStateToProps, mapDispatchToProps)(MPINScreen);
when I am click on confirm button then hide and display . But in second component data is prepopulating which i was inserted.
in this screen shot data is prepopulate but i want this empty, Because user has to insert again. but it is taking same value from previous state. how we can use multiple time same component in one page.
General idea:
Create a property in MPINScreen state that is changing (incrementing) every attempt (you can call it attempt) and pass it as prop to BoxInput.
In BoxInput create a reset function (that will clean the values of the text inputs and focus the first input). On componentDidUpdate check if attempt prop changed. If true - save the new value in BoxInput state and call "reset".

React Native Mathematical operation not working properly

I am diving to this question from my previous question here: React Native mathematical actions not working
However, I got the problem from the answer there and updated my code (I know that I did not solve the illegal state modifying, the main system is not working properly).
App.js
import React, { Component } from 'react';
import {
ActivityIndicator,
Text,
View,
StyleSheet,
FlatList,
Alert,
TouchableOpacity,
ScrollView,
TextInput
} from 'react-native';
import {
Avatar,
Card,
Button,
Divider,
ListItem,
Image
} from 'react-native-elements';
import Icon from 'react-native-vector-icons/FontAwesome';
import HTML from 'react-native-render-html';
import UserAvatar from 'react-native-user-avatar';
import { StackNavigator } from 'react-navigation';
import { createAppContainer } from 'react-navigation';
import { createStackNavigator } from 'react-navigation-stack';
import Cookies from 'universal-cookie';
import Heart from './components/heart';
const cookies = new Cookies();
class HomeScreen extends React.Component {
static navigationOptions = {
title: '',
};
constructor(props) {
super(props);
this.state = {
Loading: true,
data: [],
imageUrls: [],
isPress: false,
loveAction: '',
};
}
fetchLeash(user) {
return fetch('https://lishup.com/app/', {
method: 'POST',
headers: {
Accept: 'application/json',
'Content-Type': 'application/json',
},
body: JSON.stringify({ user }),
})
.then((response) => response.json())
.then((responseJson) => {
this.setState({ data: responseJson });
Promise.all(
responseJson.map(({ images }) => this.fetchImage(images))
).then((imageUrls) => this.setState({ imageUrls }));
})
.catch((error) => {
Alert.alert('error!');
})
.finally(() => {
this.setState({ Loading: false });
});
}
fetchImage(image) {
return fetch('https://lishup.com/app/fetch-image.php', {
method: 'POST',
headers: {
Accept: 'application/json',
'Content-Type': 'application/json',
},
body: JSON.stringify({ image }),
})
.then((response) => response.json())
.then((responseJson) =>
// Filter elements with empty string URLs, then app just the URL
responseJson.filter(({ url }) => url).map(({ url }) => url)
);
}
componentDidMount() {
this.fetchLeash(cookies.get('user'));
}
heartOnPress = (id, writer) => {
this.setState((state) => {
const data = state.data.map((el) => {
if(el.id === id) {
if(el.isLiked == true){
el.loves = el.loves - 1;
} else {
el.loves = el.loves + 1;
}
el.isliked = !el.isliked;
}
return el;
});
const isPress = !state.isPress
return { data, isPress };
});
fetch('https://lishup.com/app/love.php', {
method: 'POST',
headers: {
Accept: 'application/json',
'Content-Type': 'application/json',
},
body: JSON.stringify({
id: id,
user: cookies.get('user'),
author: writer
}),
})
.then((response) => response.json())
.then((responseJson) => {
});
};
renderLeash = ({ item, index }) => (
<View>
<Card
style={{
height: 100,
justifyContent: 'center',
alignItems: 'center',
}}>
<ListItem
leftAvatar={{
title: item.user,
source: { uri: item.userpic },
}}
title={item.user}
subtitle={item.time}
chevron
/>
<Divider style={{ margin: 5, backgroundColor: 'white' }} />
<HTML html={item.text} />
<ScrollView
horizontal={true}
>
<View style={{flex:1, flexDirection:'row'}}>
{this.state.imageUrls[index] && this.state.imageUrls[index].length
? this.state.imageUrls[index].map((uri) => (
<Image
source={{ uri }}
style={{ flex:1, width: 500, height: 500, resizeMode: 'contain'}}
PlaceholderContent={<ActivityIndicator />}
/>
))
: null}
</View>
</ScrollView>
<Text>{item.loves}</Text>
<Text>{this.state.loveAction}</Text>
<Heart isLiked={item.isliked} main={item.user} id={item.id} onPress={this.heartOnPress} />
</Card>
</View>
);
render() {
if (this.state.Loading == true) {
cookies.set('user', 'LishUp', { path: '/' });
return (
<ActivityIndicator
size="large"
style={{ marginTop: 100 }}
color="#0000ff"
/>
);
} else {
return (
<View>
<FlatList
style={{ width: 400 }}
data={this.state.data}
keyExtractor={(item, idx) => idx}
renderItem={this.renderLeash}
/>
</View>
);
}
}
}
const styles = StyleSheet.create({});
const RootStack = createStackNavigator(
{
Home: { screen: HomeScreen },
},
{
initialRouteName: 'Home',
}
);
export default createAppContainer(RootStack);
heart.js
import React from 'react';
import { View, TouchableOpacity } from 'react-native';
import Icon from 'react-native-vector-icons/FontAwesome';
const Heart = ({ isLiked, onPress, main, id }) => {
return (
<View>
{isLiked ? (
<TouchableOpacity onPress={() => onPress(id, main)}>
<Icon name="heart" size={30} color="red" />
</TouchableOpacity>
) : (
<TouchableOpacity onPress={() => onPress(id, main)}>
<Icon name="heart" size={30} color="grey" />
</TouchableOpacity>
)}
</View>
);
};
export default Heart;
The problem right is: Suppose, there is 2 loves in a post. I pressed love. It just adds 1 beside the number 2 instead of doing an addition. Like- it becomes 21 instead of being 3
I can't understand where is the mistake, does react native avoid this kind of mathematical operation?
My snack: https://snack.expo.io/#nothingtosay/privileged-toffee
First of call you can change you Heart component
import React from 'react';
import { View, TouchableOpacity } from 'react-native';
import Icon from 'react-native-vector-icons/FontAwesome';
const Heart = ({ isLiked, onPress, main, id }) => {
return (
<View>
<TouchableOpacity onPress={() => onPress(id, main)}>
<Icon name="heart" size={30} color={isLiked?"red":"grey"} />
</TouchableOpacity>
</View>
);
};
export default Heart;
and you can parse the el.loves value before adding and subtracting Like this
el.loves = parseInt(el.loves) - 1;
el.loves = parseInt(el.loves) + 1;
It is just treating your “loves” as a string. Convert to number first with parseInt:
if(el.isLiked == true){
el.loves = parseInt(el.loves) - 1;
} else {
el.loves = parseInt(el.loves) + 1;
}

JSON.stringify cannot serialize cyclic structure when passing state

I have problem when fetching data in react-native. I'm trying to send parts of my state in body of POST. I dont understand where is cyclic structure in my code. I dont see any cyclic structures.
I know the error is caused by state because when i simply put some strings in body everything is going alright.
import React from 'react';
import {Text, View, Button, StyleSheet, TextInput, TouchableOpacity} from "react-native";
export default class AddKidScreen extends React.Component {
constructor(props) {
super(props);
this.state = {
name: '',
age: '',
parentID: props.navigation.getParam('myID', 0)
}
}
handleAddKid() {
let url = "https://piotr2.scementowani.pl/apiPiotr";
let name = this.state.name;
let age = this.state.age;
fetch(url, {
method: 'POST',
headers: {
'Content-Type': "application/json",
},
body: JSON.stringify({
method: "addKid",
name: name,
age: age,
}),
})
.then(response => response.json())
.then(responseJson => {
this.props.navigation.navigate('Main');
})
.catch((error) => {
console.error(error);
});
}
updateValue(text,field) {
if (field == 'name') {
this.setState({
name: text,
})
} else if (field == 'age' ){
this.setState( {
age: text,
})
}
}
render() {
return(
<View>
<View style={{flexDirection: 'row', width: '100%'}}>
<Text>
Imię:
</Text>
<TextInput
placeholder = "Imię"
onChange = {(text) => this.updateValue(text,'name')}
/>
</View>
<View style={{flexDirection: 'row', width: '100%'}}>
<Text>
Wiek:
</Text>
<TextInput
placeholder = "Wiek"
onChange = {(text) => this.updateValue(text,'age')}
/>
</View>
<TouchableOpacity onPress={this.handleAddKid.bind(this)}>
<Text>DODAJ</Text>
</TouchableOpacity>
</View>
)
}
}
When running handleAddKid()
I get JSON.stringify cannot serialize cyclic structure.

React Native: Maximum update depth exceeded error

Am getting Maximum update depth exceeded error while entering values into the text field . This is my component .
If i remove the onChangeText event it wont throw error, so the issue is with the event .
These are the dependencies am currently using
react : 16.8.6,
react-dom :16.8.6,
react-native :https://github.com/expo/react-native/archive/sdk-33.0.0.tar.gz,
import { Form, View, Text, Button, Item, Input, Label, Toast, Spinner } from "native-base";
import React from "react";
import { validatePin } from "../services/validate";
export default class LoginForm extends React.Component {
constructor(props) {
super(props);
this.state = { userid: "", loading: "false" };
}
async login() {
if (this.state.userid.length == 0) {
Toast.show({
text: "Wrong UserID!",
buttonText: "Okay",
textStyle: { color: "yellow" }
});
} else {
if(this.state.loading === "false" ){
this.setState({ loading: "true" });
}
try {
let res = await validatePin(this.state.userid);
if (typeof res != "undefined") {
const { navigate } = this.props.navigation;
this.setState({ loading: "false" });
if (res.bypassMFA) {
navigate("Password", {
user_id: this.state.userid,
member_name: res.member_name
});
} else {
navigate("MFAComponent", {
userid: this.state.userid,
mfa_id: res.mfa_id,
mfa_q: res.mfa_q,
isValidUser: res.isValidUser
});
}
}
} catch (err) {
console.log("error in login:" + err);
}
}
}
render() {
const { navigate } = this.props.navigation;
return (
<View>
<Form style={{ padding: 5, alignItems: "center" }}>
<Item floatingLabel>
<Label>Online ID</Label>
<Input
value={this.state.userid}
onChangeText={username => this.setState({ userid: username })}
/>
</Item>
{this.state.loading == "true" ? (
<View>
<Spinner size="large" color="#c137a2" />
</View>
) : null}
<Button primary onPress={this.login} style={{ alignSelf: "center", margin: 20 }}>
<Text> Next </Text>
</Button>
</Form>
</View>
);
}
}
First of all you didn't bind login function for onPress. Your onPress props should be like this :
onPress={() => this.login}
or in constructor bind method :
this.login.bind(this)

React Native Fetch works only on second click

I do app on React Native. The problem is next :
OnPress some element i am trying make request to my server and log answer.
When I click button first time - my log do not show anything , but on second click I see response in the console.
import React from 'react'
import { View, Text, StyleSheet, TextInput , TouchableNativeFeedback , AsyncStorage } from 'react-native'
import {connect} from 'react-redux'
import * as pageActions from '../action/index'
import { bindActionCreators } from 'redux'
import api from '../api'
class Login extends React.Component {
constructor(props){
super(props);
this.state = {
loginAttempt : false,
email : 'admin#mail.ru',
password : 'password',
token : ''
}
}
loginAttempt() {
let email = this.state.email;
let password = this.state.password;
api.login(email,password)
}
render() {
return (
<View style={styles.container}>
<TextInput
placeholder="Email"
style={{height: 50, borderColor: 'gray', borderWidth: 1}}
onChangeText={(value) => this.setState({email : value})}
/>
<TextInput
placeholder="Password"
style={{height: 50, borderColor: 'gray', borderWidth: 1}}
onChangeText={(value) => this.setState({password : value})}
/>
<TouchableNativeFeedback
style={!this.state.loginAttempt ? {'opacity' : 1} : {'opacity' : 0}}
onPress={() => this.loginAttempt()}>
<View>
<Text>Try login</Text>
</View>
</TouchableNativeFeedback>
</View>
)
}
}
var styles = StyleSheet.create({
container: {
flex: 1,
justifyContent: 'center',
alignItems: 'center'
}
}
)
My fetch function
login(email,password, callback) {
const API_HEADERS = {
'Accept' : `application/json`,
'Content-Type' : `application/json`
};
let user = {};
user.email = email;
user.password = password;
fetch(`http://myIp:3000/auth/login`, {
method : 'post',
headers : API_HEADERS,
body : JSON.stringify(user)
})
.then((response) => {
if (response.ok) {
return response.json();
} else {
alert(`Wrong data`)
}
})
.then((responseData) => {
console.log(responseData)
})
}
Also wanna add that I using Genymotion as android emul.Another strange thing is that when I press my button first time - nothing happens,but when i press Reload JS , before the component will be unmount , I see my responceData in a console
You should update state, when promise resolved.
.then((responseData) => {
this.setState({
token: responseData.token
});
})
Use catch method:
.then().catch(e => console.log("error: ", e))
Also, where is your alert function? react-native has Alert module.
Alert.alert('any message text');
article about fetch
and this is article using fetch in react-native
Another strange thing is that when I press my button first time
This is very like related to focus.
Try setting keyboardShouldPersistTaps = true for TouchableNativeFeedback

Resources