0

I'm using: method = () => { } so i don't need to bind the function

here's my class:

class Form extends Component {

  constructor(props) {
    super(props);

    this.state = {
      disabledFields: [],
    };

  }

  executeCode = ( methodCode ='', params = {} ) => {
    const result = crudCode[methodCode](params);
    if (result && result.newStates) {

      Object.keys(result.newStates).map(function(keyName, keyIndex) {
          this.setState( {  nada: 'nada' });
        });
    }
  }

I get this error:

TypeError: Cannot read property 'setState' of undefined
> 48 |         this.setState( {  nada: 'nada' });

what I'm doing wrong, I've already used this type of function and setState, but i don't know this time it does not work.

Ishan Patel
  • 5,571
  • 12
  • 47
  • 68
DDave
  • 1,400
  • 3
  • 16
  • 33
  • 1
    Possible duplicate of [How to access the correct \`this\` inside a callback?](https://stackoverflow.com/questions/20279484/how-to-access-the-correct-this-inside-a-callback) – Andrew Li Dec 27 '17 at 00:52

1 Answers1

5

You don't use an arrow function in your map callback:

Object.keys(result.newStates).map(function(keyName, keyIndex) {
    this.setState( {  nada: 'nada' });
});

So, it is not bound to this.

This will work instead:

Object.keys(result.newStates).map((keyName, keyIndex) => {
    this.setState( {  nada: 'nada' });
});
Davin Tryon
  • 66,517
  • 15
  • 143
  • 132