Nux
Nux

Reputation: 7078

Maximum update depth exceeded react

I am well aware that we should never setState inside render method because it will lead to infinite loops.

I am showing Modal in my app which has edit form. When form is submitted loading status is displayed inside modal and same way for errors. But if everything is fine and some data has been returned from server I want to hide the Modal. How to make this work?

Codes.

//Function to close the modal.
closeEditModal = () => this.setState({openEditModal: false});

render() {
    const {openEditModal, formTitle, categoryId} = this.state;

    return <Mutation
        mutation={EDIT_CATEGORY}>
        {(mutate, {called, loading, error, data}) => {

            //Close modal after successful mutation
            if (data) this.closeEditModal(); //THIS CAUSE ERROR WHEN DATA IS RETURNED.

            return <Modal size='tiny' open={openEditModal} onClose={this.closeEditModal}>
                <Modal.Header>Edit Form</Modal.Header>
                {error ? <Modal.Content>{error}</Modal.Content> : null}
                <Modal.Content>
                    <Form onSubmit={e => {
                        e.preventDefault();
                        mutate({variables: {categoryId: categoryId, input: {title: formTitle}}})
                    }} loading={loading} >
                        {/*FORM INPUTS HERE*/}
                    </Form>
                </Modal.Content>
            </Modal>;
        }}
    </Mutation>
}

Note: I am using apollo client to submit data.

Upvotes: 1

Views: 234

Answers (2)

Kunsang Dorjee
Kunsang Dorjee

Reputation: 39

Please try, enclosing the function body.

closeEditModal = () => {
this.setState({openEditModal: false}); }

Upvotes: -1

Mayank Shukla
Mayank Shukla

Reputation: 104369

You need to modify the condition because once you have the data, it will call the closeEditModel in a loop, and that will throw this error:

Maximum update depth exceeded

Use this condition and call the closeEditModel method only once:

if (data && this.state.openEditModal)
  this.closeEditModal();

Upvotes: 2

Related Questions