Reputation: 2837
I have the following code, on my component mount but I'm getting set state is not a function error which I know is a binding issue but I'm not where I should be doing the binding?
const selectedTag = this.props.tag;
// Checks to see if this should be selected
let checkSelected = function(arr, val) {
_(arr).each(function(value) {
if (value == val) {
this.setState({checked: true})
}
});
};
checkSelected(this.props.selectedTags, selectedTag)
console.log(this.state.checked)
Upvotes: 0
Views: 58
Reputation: 93421
Use arrow function to keep the scope of this
intact :
let checkSelected =(arr, val) => {
_(arr).each((value) => {
if (value == val) {
this.setState({checked: true})
}
});
};
and NOT :
let checkSelected = function(arr, val) {
_(arr).each(function(value) {
if (value == val) {
this.setState({checked: true})
}
});
};
Upvotes: 2
Reputation: 4565
Try declare global this outside the each func and use it
var _this = this; // Reference
let checkSelected = function(arr, val) {
_(arr).each(function(value) {
if (value == val) {
_this.setState({checked: true})
}
});
};
Upvotes: 0