【问题标题】:Apollo/graphql request result buffered in vuejs在 vuejs 中缓冲的 Apollo/graphql 请求结果
【发布时间】:2021-10-04 08:47:28
【问题描述】:

在控制用户订阅时事通讯的 Vue 组件中,我有同伴代码:

async newSubscriber(event) {
  // Validate email
  //---------------
  if (!this.isEmailValid(this.subscriber_email))
      this.subscribeResult = "Email not valid";
  else {
    // If valid, check if email is not already recorded
    //-------------------------------------------------
    let alreadyRecorded = false;
    let recordedEmails = await this.$apollo.query({ query: gql`query { newslettersEmails { email } }` });
    console.log('length ' + recordedEmails.data.newslettersEmails.length);
    console.log(recordedEmails.data.newslettersEmails);
    for (let i = 0; !alreadyRecorded && i < recordedEmails.data.newslettersEmails.length; i++)
      alreadyRecorded = this.subscriber_email === recordedEmails.data.newslettersEmails[i].email;
    if (alreadyRecorded)
      this.subscribeResult = "Email already recorded";
    else {
      // If not, record it and warn the user
      //------------------------------------
      this.$apollo.mutate({
        mutation: gql`mutation ($subscriber_email: String!){
          createNewslettersEmail(input: { data: { email: $subscriber_email } }) {
            newslettersEmail {
              email
            }
          }
        }`,
        variables: {
          subscriber_email: this.subscriber_email,
        }
      })
      .then((data) => { this.subscribeResult = "Email recorded"; })
      .catch((error) => { this.subscribeResult = "Error recording the email: " + error.graphQLErrors[0].message; });
    }
  }
}

在第一次电子邮件订阅测试中,$apollo.query 会返回已记录的正确电子邮件数量(比如 10 封)并记录新订阅者的电子邮件。但是,如果我尝试在不硬刷新 (F5) 浏览器的情况下记录第二封电子邮件,$apollo.query 会返回与第一次 (10) 完全相同的结果,即使 Strapi (graphql) 正确记录了第一封测试电子邮件palyground 向我展示了添加的带有相同查询的电子邮件!)。即使我添加了 10 封电子邮件,apollo 也总是会返回它在第一次调用时收到的内容(10 封记录的电子邮件),就好像它使用了缓冲结果一样。当然,这允许 Vue 多次记录同一封电子邮件,我显然想避免这种情况!

它会和任何人说话吗?

【问题讨论】:

    标签: vue.js graphql strapi vue-apollo


    【解决方案1】:

    经过大量的谷歌挖掘(通过简单地改变我的请求来给出想要的结果,最后,通过“缓存”来“缓冲”!),我了解到 Apollo 默认缓存它的查询(至少,在我收到的 Vue 项目的配置)。为了解决这个问题,我刚刚在我所做的查询中添加了“fetchPolicy: 'network-only'”:

    let recordedEmails = await this.$apollo.query({
      query: gql`query { newslettersEmails { email } }`,
    });
    

    成为

    let recordedEmails = await this.$apollo.query({
      query: gql`query { newslettersEmails { email } }`,
      fetchPolicy: 'network-only'
    });
    

    问题解决了^^

    【讨论】:

      猜你喜欢
      • 2019-07-23
      • 2019-07-26
      • 2018-11-02
      • 2018-10-21
      • 1970-01-01
      • 2021-05-07
      • 2017-03-16
      • 1970-01-01
      • 2019-06-11
      相关资源
      最近更新 更多