【问题标题】:Apollo writeFragment not updating dataApollo writeFragment 不更新数据
【发布时间】:2018-07-15 20:42:53
【问题描述】:

在 react-apollo 2.0.1 中,我有一个如下所示的 graphql 类型:

type PagedThing {
  data: [Thing]
  total: Int
}

当做下面的writeFragment时

  client.writeFragment({
    id,
    fragment: gql`
      fragment my_thing on Thing {
        status
      }
    `,
    data: {
      status
    }
  })

缓存未更新,新数据未显示在 UI 上。还有什么需要做的吗?

PS:为了安全起见,我使用了fragment matching

编辑 1:

我收到以下错误:

无法匹配片段,因为缺少 __typename 属性:{"status":"online"}

所以我把代码改成:

client.writeFragment({
    id,
    fragment: gql`
      fragment my_thing on Thing {
        status
      }
    `,
    data: {
      __typename: 'Thing',
      status
    }
  })

并且没有抛出错误,但更新仍然没有发生

【问题讨论】:

  • 关闭页面。立即,匆忙地重新回应,以确保我对问题和答案都投了赞成票。唷。

标签: caching graphql react-apollo


【解决方案1】:

事实证明,我不仅需要添加 __typename 作为默认解析的 ID(解释为 here

所以我需要执行以下操作才能使其正常工作:

client.writeFragment({
  id: `Thing:${id}`,
  fragment: gql`
    fragment my_thing on Thing {
      status
    }
  `,
  data: {
    __typename: 'Thing',
    status
  }
})

【讨论】:

  • id 前加上类型名是关键,谢谢!
  • 这个方法的文档还有很多不足之处,不得不说。
  • 链接对我来说已经失效了。解释是什么?
  • 用一些等价物更新了链接。原因是 ID 与默认解析的 ID 与 __typename 不匹配,尽管在示例中它只在 writeQuery 上添加 __typename 在回答时需要将其添加到 writeFragment 上。不确定是否没有 __typename 适用于 writeFragment现在
【解决方案2】:

该框架似乎已扩展为提供一个名为“identify”的方法来避免此问题(以防他们稍后更改实现)

cache.modify({
  id: cache.identify(myPost),
             ^
  fields(fieldValue, details) {
    return details.INVALIDATE;
  },
});

https://www.apollographql.com/docs/react/caching/cache-interaction/#example-invalidating-fields-within-a-cached-object

【讨论】:

    猜你喜欢
    • 2021-04-04
    • 2019-12-29
    • 2022-07-21
    • 2018-09-26
    • 2020-02-28
    • 2020-06-04
    • 1970-01-01
    • 2020-12-19
    • 2020-07-24
    相关资源
    最近更新 更多