I'm rookie in React Native, Just started Learning it. I want to build Android App using React Native.
Now, I have a basic login form which will send fetch request to server and show if user is authorized or not.
but when I try to Alert the value of input field it throws error "Undefined is not an object"
I am referring to official docs here , This code is working. I have also tried basic react form here . I am using UI kitten text input for inputs, I have also used native react TextInput, it gave same error.
My current code is:
import React from 'react';
import { Alert, StyleSheet, Text, TextInput, View } from 'react-native';
import {RkButton, RkText, RkTextInput, RkCard} from 'react-native-ui-kitten';
import Icon from 'react-native-vector-icons/Ionicons';
export default class App extends React.Component {
constructor(props) {
super(props);
this.state = {
username: '',
password: ''
};
this.handleChange = this.handleChange.bind(this);
}
handleChange(event) {
const target = event.target;
this.setState({
username: target.username,
password: target.password
});
}
login()
{
Alert.alert(this.state.username) //getting error here
let data = {
method: 'POST',
credentials: 'same-origin',
mode: 'same-origin',
body: JSON.stringify({
username: this.state.username,
password: this.state.password
}),
headers: {
'Accept': 'application/json',
'Content-Type': 'application/json',
}
}
fetch('http://demourl.com/login',data)
.then((response) => response.json())
.then((responseJson) => {
if (responseJson.success == 'true') {
Alert.alert('Login Successfull!')
}
else {
Alert.alert('Login Failed')
}
})
.catch((error) => {
console.error(error);
});
;
}
render() {
return (
<View style={styles.container}>
<RkCard style={{padding: 20}}>
<View style={{alignItems: 'center',padding: 10}}>
<RkText rkType='warning large' style={{fontSize: 40}}>Log In</RkText>
</View>
<View style={{alignItems: 'center',padding: 10}}>
<RkTextInput placeholder='Username' value={this.state.username} onChange={this.handleChange} />
<RkTextInput placeholder='Password' value={this.state.password} onChange={this.handleChange}/>
</View>
<View style={{alignItems: 'center',padding: 10}}>
<RkButton rkType='success small' title="Press Me"
onPress={this.login}
>Log In!</RkButton>
</View>
</RkCard>
</View>
);
}
}
const styles = StyleSheet.create({
container: {
marginTop: 65,
backgroundColor: '#fff',
justifyContent: 'center',
padding: 10
},
});
Please tell me where I'm failing to understand the working. or where my code is buggy. Thanks In advance.