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.

1

1 Answer 1

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' });
});
Sign up to request clarification or add additional context in comments.

1 Comment

If you don't mind, could you use your gold badge to mark as duplicate?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.