Reputation: 131
I'm trying to make a basic login screen. However, I'm struggling with the e-mail validation.
Every time I press a button, I want to make sure that the user inputs the correct e-mail format, or give them a small alert under the e-mail TextInput if they write something other than a valid e-mail (this alert will be hidden by default.). However, when I try, it always gives me this error (regardless of the user input):
undefined is not an object (evaluating 'this.state.username')
This is my code so far
class HomeScreen extends Component {
state = { username: null, password: null }
show = false;
_validar = (text) => {
let reg = /^\w+([\.-]?\w+)*@\w+([\.-]?\w+)*(\.\w{2,3})+$/ ;
if(reg.test(text) === false) {
return false;
} else {
return true;
}
}
_onSubmit() {
if(this._validar(this.state.username) == true) {
const { username, password } = this.state;
} else {
this.show = true;
}
}
render() {
return (
<KeyboardAwareScrollView contentContainerStyle={styles.container} scrollEnabled
enableOnAndroid={true} resetScrollToCoords={{x:0, y:0}}>
<View style={styles.logo}>
<Image source = {logo} style={styles.img}/>
<Text style={styles.textLogoPrimary}>Neuron App</Text>
<Text style={styles.textLogoSecondary}>Test</Text>
</View>
<View style={styles.formElement}>
<Text style={styles.formText}>Correo Electrónico</Text>
<TextInput keyboardType='email-address' placeholder='Email' onChangeText={value => this.setState({ username: value })}
style={styles.formInput} />
{this.state.show ? (
<Text style={styles.textAlert}>Correo Electrónico no valido.</Text>
) : null}
</View>
<View style={styles.formElement}>
<Text style={styles.formText}>Contraseña</Text>
<TextInput style={styles.formInput} onChangeText={value => this.setState({ password: value })} secureTextEntry={true}/>
</View>
<View style={styles.buttonView}>
<TouchableOpacity style={styles.button} onPress={this._onSubmit}>
<Text style={styles.buttonText}>Iniciar</Text>
</TouchableOpacity>
</View>
</KeyboardAwareScrollView>
);
}}
Upvotes: 1
Views: 112
Reputation: 695
This error is raised because you are accessing the this.state.username
before it is assigned. I would recommend you to change the initial state value of username
into a string, as it ends up being a string, instead of null
.
state = { username: '', password: '' };
null
can be avoided in string case, by just assigning it ''
an empty string. If you are to evaluate it logically, it would give you same result as null
as it is 'falsy'.
Upvotes: 0
Reputation: 12215
Just change your onSubmit funciton to "
_onSubmit = () =>{
if(this._validar(this.state.username) == true) {
const { username, password } = this.state;
} else {
this.show = true;
}
}
ES^ binds this automatically. Hope it solves the error
Upvotes: 1