Search code examples
javascriptreactjsmodal-dialogreact-modal

Access variable modified in function in render method


I have the following code (trimmed the form and some other boilerplate):

import React, { Component } from 'react';
import Modal from 'react-modal';

var responseMessages;
export default class ContactForm extends Component {

handleSubmit(event) {
    responseMessages = []

    fetch('http://127.0.0.1:4000/test', {
        method: 'POST',
        mode: 'cors',
        headers: {
            "Access-Control-Allow-Origin":"*",
            'Content-Type': 'application/json'
            },
        body: JSON.stringify(data)
    }).then((response) => response.json())
    .then((responseJson) => {
        for(var i = 0; i < responseJson.errors.length; i++) {
            responseMessages.push(
                <p>{responseJson.errors[i].msg}</p>
            );
        }
    })
    .then(this.openModal());
}

render() {
  return (
    <div>
    <Modal  isOpen={this.state.modalIsOpen}
            onRequestClose={this.closeModal}
            ariaHideApp={false}
            style={customStyles}>
            <div>
                {responseMessages}
            </div>
   </Modal>
   </div>
)}}

Adding {responseMessages} in the Modal displays nothing, but if I change it to {console.log(responseMessages)} it shows in the console that responseMessages is not empty (it has different length, but not empty) What could be the reason for that?

EDIT: openModal function:

openModal() {
    this.setState({modalIsOpen: true});
}

ResponseJson:

{"errors":[{"location":"body","param":"message","msg":"error message","value":"entered value"}]}

Solution

  • This is a javascript issue and has nothing to do with react. when you write .then(this.openModal()) the openModal function will be called immediately. So the actual code should be

    .then(this.openModal.bind(this));

    or using arrow function

    or .then(() => this.openModal());

    if you are using some autobind decorator or if you are binding functions inside constructor then simply .then(this.openModal); should also work.