Reputation: 313
Hi i'm not verry good using react and i don't understand why my this.setState dont work here but on some other files it is. On my other files it is written exactly the same and it works but not here. Can someone tell me why ?
test(event){
event.preventDefault();
var regex_mongoinclude = document.getElementById("regexinclude").value;
var regex_mongoexclude = document.getElementById("regexexclude").value;
if (this.props.item.type == "email") {
(function(prop) {
var text = document.getElementById("name_sub").value;
var reg = /^([a-zA-Z0-9.\-_]+[@]{1}[a-zA-Z0-9\-_]+[.]{1}[a-zA-Z0-9\-_]+[,]*)+/;
if(reg.test(text)==true) {
Subs.update(
{ _id: prop.item._id },
{
text,
type :"email",
createdAt: new Date(),
regex_mongoinclude,
regex_mongoexclude,
topic:prop.parent._id,
},
{ upsert: true }
)
this.setState({
showMessage: true,
isError: false
});
} else {
this.setState({
showMessage: true,
isError: true
});
}
})(this.props)
} else if (this.props.item.type == "slack") {
Upvotes: 1
Views: 86
Reputation: 190
'test' function seems to be an event handler.
this
inside an event handler has to be binded manually in the component contructor with something like:
// inside constructor
this.test = this.test.bind(this)
After that this.setState
will work hopefully.
Upvotes: 0
Reputation: 21694
In this line:
(function(prop) {
You're creating a new closure, essentially losing the reference to the correct this
object. You could replace it with:
((prop) => {
The arrow function keeps the correct closure intact.
But honestly, I'm not sure why you even need it in this case, you could put your code directly in the if
statement and wouldn't need to create an IIFE.
Upvotes: 3