Search code examples
javascriptreactjsantdant-design-proreact-class-based-component

Cannot access this.setState or this.state inside Ant Modal confirm ok/cancel function


I'm having issues with accessing this.state and this.setState inside the onCancel/onOk function. I want to modify the state after confirmation or canceling the pop-up modal. If anyone's got a different approach, your guidance would be helpful.

import React from 'react';
import { Button, Modal } from 'antd';

class ExampleClass extends React.Component {
  constructor() {
    super();

    this.state = {
      bankInfo: 100,
    };
  }

  onButtonClicked() {
    this.setState({ bankInfo: 200 });            // works fine
    Modal.confirm({
      title: 'Are you sure delete this item?',
      okType: 'danger',
      onOk() {
        this.setState({ bankInfo: 300 }); // Uncaught TypeError: Cannot read property 'setState' of undefined
      },
      onCancel() {
        this.setState({ bankInfo: 400 }); // Uncaught TypeError: Cannot read property 'setState' of undefined
      },
    });
  }

  render() {
    return (
      <div>
        <Button onClick={this.onButtonClicked.bind(this)}>Click Me</Button>
      </div>
    );
  }
}

export default ExampleClass;

Solution

  • I would prefer to use arrow function

    import React from 'react';
    import { Button, Modal } from 'antd';
    
    class ExampleClass extends React.Component {
      constructor() {
        super();
    
        this.state = {
          bankInfo: 100,
        };
      }
    
      onButtonClicked = () => {
        this.setState({ bankInfo: 200 });
        Modal.confirm({
          title: 'Are you sure delete this item?',
          okType: 'danger',
          onOk: () => {
            this.setState({ bankInfo: 300 });
          },
          onCancel: () => {
            this.setState({ bankInfo: 400 });
          },
        });
      }
    
      render() {
        return (
          <div>
            <Button onClick={this.onButtonClicked}>Click Me</Button>
          </div>
        );
      }
    }
    
    export default ExampleClass;