Home > front end >  How to close a modal when submit a form successfully?
How to close a modal when submit a form successfully?

Time:12-22

I have a popup. When a user enters the page for the first time, a modal shows up.

This modal has a form and this form is required to fill. When user fill the form and enter a different page, the modal is not opening, it is okey too. So, my modal work perfectly fine. It opens automatically and the user cannot close it. But here is the problem, I cannot close it too! What I want is when the user sends the form and when it returns 200 OK, the modal will close.

How can I do it?

let handleSubmit = async (e) => {
    e.preventDefault();
    try {
      let res = await fetch(
        process.env.REACT_APP_ENDPOINT   "user/me/contract",
        {
          method: "POST",
          headers: {
            "Content-Type": "application/json",
            Authorization: `Bearer ${localStorage.getItem(
              "fray_access_token"
            )}`,
          },
          body: JSON.stringify({
            name: name,
            surname: surname,
            email: email,
          }),
        }
      );
      let resJson = await res.json();
      if (res.status === 200) {
        console.log("CLOSE THE MODAL IN HERE");
        console.log("CLOSE THE MODAL IN HERE");
        console.log("CLOSE THE MODAL IN HERE");
      } else {
        console.log("Some error occured");
      }
    } catch (err) {
      console.log(err);
    }
  };

...
return(..
<Modal backdrop="static" isOpen={!modalOpen} size="lg" id="modal">
          <ModalHeader>Hoşgeldiniz!</ModalHeader>
          <ModalBody>
<Input
                      required
                      type="text"
                      value={name}
                      placeholder="İsim"
                      onChange={(e) => setName(e.target.value)}
                    />
...
...
</ModalBody>
</Modal>

CodePudding user response:

If your state is like this:

const [modalOpen, setModalOpen] = useState(false)

than you need to do this:

if (res.status === 200) {
      setModalOpen(false)
      } else {
  • Related