Reputation: 13
I'm new to React and I'm trying to update a value in a page after receiving the error message from the signup. I start with an empty value and as soon as I receive the new one I would like to display it on screen. When I try to update the state it gives me an error
TypeError: undefined is not an object (evaluating 'this.setState').
It happens only when I add this.setState({ error: errorMessage})
inside the catch.
Here's the code.
export default class Signup extends React.Component {
constructor(props) {
super(props);
this.state = {
email: '',
password: '',
error: ''
};
}
signUpUser = (email, password) => {
firebase.auth().createUserWithEmailAndPassword(email, password)
.then(function (user) {
console.log("Created new user " + user.user.providerData[0].uid)
})
.catch(function (error) {
let errorCode = error.code;
let errorMessage = error.message;
console.log(errorCode)
console.log(errorMessage)
this.setState({error: errorMessage})
})
}
render() {
return(
<View style={styles.container}>
<Text>{this.state.error}</Text>
<TextInput
style={styles.forms}
onChangeText={email => this.setState({ email })}
placeholder = "email"
/>
<TextInput
style={styles.forms}
onChangeText={password => this.setState({ password })}
placeholder = "password"
/>
<Button
title="SIGNUP"
onPress={() => this.signUpUser(this.state.email, this.state.password)}
/>
</View>
)
}
}
Upvotes: 1
Views: 146
Reputation: 85
Use arrow functions.
change your code to my code.
signUpUser = (email, password) => {
firebase.auth().createUserWithEmailAndPassword(email, password)
.then(user => {
console.log("Created new user " + user.user.providerData[0].uid)
})
.catch(error => {
let errorCode = error.code;
let errorMessage = error.message;
console.log(errorCode)
console.log(errorMessage)
this.setState({error: errorMessage})
})
}
Upvotes: 1
Reputation: 600131
Inside a function() { ... }
the meaning of this
is different from outside of that function.
The simplest fix is to use =>
notation to declare those functions, as you already do elsewhere:
firebase.auth().createUserWithEmailAndPassword(email, password)
.then((user) => {
console.log("Created new user " + user.user.providerData[0].uid)
})
.catch((error) => {
let errorCode = error.code;
let errorMessage = error.message;
console.log(errorCode)
console.log(errorMessage)
this.setState({error: errorMessage})
})
Also see:
Upvotes: 1