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.
if (data && this.state.openEditModal), otherwise it will call the same function in loop that will cause overflow. - Mayank Shukla