提交表单后执行异步功能

时间:2019-07-20 07:56:49

标签: forms gatsby netlify

我要做什么:

在我的网站上,我创建了一个注册表,希望在提交后执行以下两项操作:

1)为用户订阅MailChimp EDM列表(仅使用“名称”,“电子邮件”字段)。

2)通过执行POST操作(所有字段,尤其是其消息)将完整的表单存储在Netlify中

这是我的表格:

<form
  className={`contact-form ${submitError ? 'has-error' : ''}`}
  name={formName}
  method="POST"
  onSubmit={event => this.submitHandler(event)}
  action="/thank-you/"
  data-netlify="true"
  data-netlify-honeypot="bot-field"
>
   // Form fields
</form>

这是我的onSubmit处理程序:

submitHandler = async (event) => {
  const {
    email,
    fieldValues,
    submitting,
  } = this.state;
  if (submitting) return false;
  this.setState({
    submitting: true,
    submitError: false,
  });
  const result = await addToMailchimp(email, fieldValues);
  if (result.result === 'success') {
    // Inconsequential, as success should result in redirection to the success page
    this.setState({
      submitting: false,
    });
  } else {
    event.preventDefault(); // this SHOULD stop form submit?
    this.setState({
      errorMessage: decodeEntities(result.msg),
      submitError: true,
      submitting: false,
    });
  }
}

这是怎么回事:

如您在代码段中所看到的,为了实现这一点,我试图首先用用户提交的字段异步地将用户订阅到MailChimp中,如果我没有收到成功消息,则中断提交操作与event.preventDefault();

作为奖励,这对于防止重复注册也很有用,因为如果MailChimp已经在订阅列表中,我会收到一条消息。

问题:

但是,无论订阅操作是完成,成功还是失败,表单都会提交并重定向到成功页面(/thank-you/)。

我大约有50%的表单提交导致MailChimp订阅,而另一半则没有。当我最终进行测试时,有时会在页面重定向到成功页面(/thank-you/)之前看到订阅成功/失败消息的闪烁。

值得注意的是,event.preventDefault();会破坏表单提交操作,前提是它是在异步/等待功能之前执行的-因此,我认为这与执行订阅操作所需的时间有关。

有人能阐明这里发生的事情和潜在的解决方案吗?

1 个答案:

答案 0 :(得分:2)

您能否在Map<String, List<Long>> map = personList.stream() .collect(groupingBy( Person::getDepartment, mapping(Person::getTimestamp, collectingAndThen(toCollection(() -> new TreeSet<>(Comparator.comparingLong(Person::getTimestamp))), ArrayList::new)))); 之前preventDefault,然后在从对await的异步调用中获得成功之后,再在表单上调用submit()

addToMailchimp

working codesandbox example

相关问题