Search code examples
reactjschakra-ui

How to trigger close modal in Chakra UI?


I am using Modal Component in Chakra UI to show Input editor post (Input editor is a children component wrapped by Modal component). I want to trigger close modal from Input editor component if data was fetched as succeed.

Here's my component for Modal:

//...import component from Chakra Modal
import {Post as PostModal} from '../components/Modal'

export const Post = () => {

  const { isOpen, onOpen, onClose } = useDisclosure()

  return (
    <div>
  <Modal onClose={onClose} size='full' isOpen={isOpen} trapFocus={false} >
    <ModalOverlay />
    <ModalContent>
      <ModalHeader>Add Post</ModalHeader>
      <ModalCloseButton />
      <ModalBody>
        <div>
          <PostModal />
        </div>
      </ModalBody>
    </ModalContent>
  </Modal>
    </div>
  )
} 

And my code handle fetcher post data:

/components/Modal

const fetcher = async (data) => {
  const _ = await sendPost(data);
  if (_) {
    //here i want to trigger close modal
  }
}

const PostInput = () => {
  return (
    //<Input/>
    //<Textarea> etc...
  )
}

Who can help me please?


Solution

  • You can call the onClose function once the API call is successful , as:

    const fetcher = async (data) => {
      let res = await sendPost(data);
      if (res.data) {
        onClose()
      }
    }