Home > other >  How to wait for response before going to next action?
How to wait for response before going to next action?

Time:12-01

I have a function which is responsible to save data in strapi cms which will generate an id and with that id I want to invoke another function.

The problem is, that once user clicks the button, data is being sent to the cms and without waiting the id to be returned, it proeeds with the other action.

In my case the other action is sending an email, and when I send the email, the id is not returned so I get undefined. But once user clicks the second time, id already there and email can be sent successfully.

My goal is to wait until id is already available and only then send an email.

Here is the code where I am saving the data via apollo-client and getting the id: called newID.

const [newID, setNewID] = useState<number>();

const [addProject, { loading }] = useMutation(PROJECT_MUTATION, {
  onCompleted(data) {
    setSubmitted(true);
    setNewID(data.createdProject.data.id); // I am getting the id here
  },
  one rror() {
    setError(true);
  },
});

useEffect(() => {
  if ( imageUploaded ) {
    addProject({
      variables: {
        title: formData.uploaderMail
      },
  })
    .catch((error) => {
      setError(true);
    })
    .then(() => {
      setSubmitted(true);
     });
   }
  }, [ addProject, formData.uploaderMail]);

And here I am trying to send an email with the id that should be returned and saved in setNewId setter function.

const sendDEmailHandleClick = useCallback(() => {
  if (newID && formData.uploaderMail) {
    sendEmail(
      formData.uploaderMail,
      newID // here on the first click id is undefined
    );
    setEmailError("");
  } else {
    setEmailError("Something went wrong");
  }
}, [ formData.uploaderMail, newID ]);

sendEmail is just a function which expects to arguments to be sent

const sendEmail = async (uploaderMail, id) => {
  const sendEmail = await fetch(
    `/api/req/${uploaderMail}/${id}`,
    {
      method: "POST",
      headers: {
        "Content-Type": "application/json",
      },
    }
  );
};

And button responsible for sending the email.

<Button
  type="submit"
  onClick={sendDEmailHandleClick}
>
  Send email
</Button>

CodePudding user response:

call sendDEmailHandleClick in id change rather than the click event.

useEffect(() => {
  if(newID){
    sendDEmailHandleClick()
  }

}, [newID])
  • Related