2

I have a React.Component inside a ReactModal.

class Course extends React.Component {
  constructor(props) {
    super(props)
    this.state = {
      isModalOpen: false,
    }
  }
  handleModalOpen = event => {
    this.setState({ isModalOpen: true })
  }

  handleModalClose = event => {
    this.setState({ isModalOpen: false })
  }

  render() {
     <ReactModal
          isOpen={this.state.isModalOpen}
          onRequestClose={this.handleModalClose}
          contentLabel="Purchase a Course"
          style={customStyles}>
        <CheckoutComponent handleClose={this.handleModalClose}/>
     </ReactModal>

   class CheckoutForm extends React.Component {
    constructor(props) {
        super(props);
    }

    handleSubmit = (ev) => {
       axios.post(`${process.env.API_URL}purchase`, charge)
          .then(function (response) {
              this.props.handleClose();
          }
  }

I would like to close the react modal upon successful post of the http request.

However, this is undefined.

How can I do it?

Emile Bergeron
  • 17,074
  • 5
  • 83
  • 129
Dejell
  • 13,947
  • 40
  • 146
  • 229
  • 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) – Emile Bergeron May 30 '19 at 17:27

1 Answers1

1

The problem is in here

axios.post(`${process.env.API_URL}purchase`, charge)
          // here
    .then(function (response) {
        this.props.handleClose();
    })

You need to use arrow functions. With normal functions, this will the the annonimous function's this. Using arrow functions solve this problem and you get the component's this.

axios.post(`${process.env.API_URL}purchase`, charge)
          // arrow function
    .then(response => {
        this.props.handleClose();
    })

This answer explain it well.

Vencovsky
  • 28,550
  • 17
  • 109
  • 176