Almog
Almog

Reputation: 2837

React Native Set State not a function, in a for each loop not sure about binding?

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

Answers (2)

Abdennour TOUMI
Abdennour TOUMI

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

digit
digit

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

Related Questions