I have this code inside a class method:
ref
.orderByValue()
.equalTo(email)
.once("value", snapshot => {
if (snapshot.exists()) {
console.log(this);
this.setState({ signedUp: true });
} else {
ref.update({ [newKey]: email });
}
});
It's going to update my Firebase database on submit, unless the user has already signed up. A typeError says this.setState is not a function
. But when I console log this
, the console prints out the class. Logging this.state
also prints out the state.
How do I fix this? I want to update my state from inside this function.
The best solution is to use functional component.
However if you want to use class component, this is probably a binding issue.
So if this is triggered inside function named func
, you should bind this function inside the constructor.
...
constructor(props) {
...
this.func = this.func.bind(this);
...
}
func() {
...
ref
.orderByValue()
.equalTo(email)
.once("value", snapshot => {
if (snapshot.exists()) {
console.log(this);
this.setState({ signedUp: true });
} else {
ref.update({ [newKey]: email });
}
});
...
}
If you don't want to bind this function, you should use arrow function.
func = () => {
...
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.