Search code examples
javascriptreactjsstateag-gridprop

comparing state and prop value - error: cannot read property 'state' of undefined


I have two arrays (one in a state and one is a prop) and both have key:value pairs

if i use:

this.props.test.col.forEach(function(element){
    console.log(element.header);
}

I will see a list of all the header values in the array of key:value pairs within my prop

If I use:

console.log(this.state.gridOptions.api.blahhhh.hasOwnProperty('example header');

it will return true if the key of one of the key:value pairs in my state is 'example header'

Both work as expected. I want to compare the state and prop key:value pairs and perform an action every time the key in the key:value pair of my state matches the value of the key:value pair of my prop.

So why does the below not work? All i did was combine the two

this.props.test.col.forEach(function(element){
    if (this.state.gridOptions.api.blahhhh.hasOwnProperty(element.header)){
    console.log('hi');
    }
}

I get the error:

Uncaught TypeError: Cannot read property 'state' of undefined 

In the example code above, if there is a match between the value and the key of the state and prop, then print 'hi' to console


Solution

  • using 'this.' inside the forEach-callback will have another context.

    let's try:

    let self=this;
    this.props.test.col.forEach(function(element){
        if (self.state.gridOptions.api.blahhhh.hasOwnProperty(element.header)){
        console.log('hi');
        }
    }