【问题标题】:React Apollo: Store updates after mutation but the ui does not reflect the changeReact Apollo:突变后存储更新,但 ui 不反映更改
【发布时间】:2018-08-02 12:30:28
【问题描述】:

我创建了一个带有以下架构的 graphQL 服务器:

...
#charts interface
interface Chart {
  id: String!
  sql: String!
  title: String
  type: String!
  display: String!
}
type Layout{
  # Unique layout id
  id: String
  # The title displayed on the layout tab
  title: String
  # List of displayed charts
  charts: [Chart]
}
...

在我的客户端上,我有一个带有以下 gql 查询的 <SummaryLayout/> 组件:

gql`{
layout(id:"summary"){
  title
  charts {
    id,
    title,
    type,
    display
  }
}}`

加载页面时,布局组件将所有图表显示为页面上的网格。用户稍后可以添加新图表,因此我有 2 个突变:一个创建图表,另一个是将新图表添加到布局中:

const addToLayout = gql`
mutation addToLayout($layoutID: String!, $chartID: String!) {
  addToLayout(layoutID: $layoutID ,chartID:$chartID){
    id
    charts {
      id
      sql
      title
      type
      display
    }
  }
}`;

const addChart = gql`
mutation addChart($chartConfig:ChartConfig!) {
  addChart(chartConfig:$chartConfig){
    id
    display
  }
}`;

this.props.addChart({
    variables: {chartConfig: chartConfig}
    }).then((response) => {
       const chartID = response.data.addChart.id;
       console.log("Chart added, DB ID:", chartID);
       this.props.addToLayout({
            variables: {layoutID: "summary", chartID: chartID},
            update: (store, data) => {
              console.log("STORE:",store);
            }
          }).then((response) => {
            appState.toggleDialog(false);
          })
     });

当我登录商店时,我可以看到 Layout:summary 条目已更新,但它没有反映在 UI 中,弹出的另一件事是还有另一个名为 $ROOT_QUERY.layout({"id":"summary"}) 的条目未使用新数据:

我错过了什么?

【问题讨论】:

    标签: reactjs graphql store apollo-client


    【解决方案1】:

    From the docs:

    默认情况下,InMemoryCache 将尝试使用常见的主键 id 和 _id 作为唯一标识符,如果它们与对象上的 __typename 一起存在。

    如果未指定 id 和 _id,或者未指定 __typename,InMemoryCache 将回退到查询中对象的路径,例如 ROOT_QUERY.allPeople.0 表示 allPeople 根查询返回的第一条记录。这将使给定类型的数据成为 allPeople 查询的范围,而其他查询必须获取它们自己的单独对象。

    Apollo 使用该生成的密钥来确定当您的突变被解决时要更新的内容。归结为,您的查询和突变都需要包含 id。这样,两者使用的生成密钥将相同。在您的代码中,突变似乎包含布局的 id,但查询不包含。

    如果由于某种原因,id 不可用,您可以使用dataIdFromObject 选项来标识要关闭的其他字段。

    【讨论】:

    • 谢谢我去看看,我觉得properties里面的id就够了。
    • 完美!这就是我所缺少的
    猜你喜欢
    • 2019-12-05
    • 2018-11-02
    • 2019-09-22
    • 1970-01-01
    • 2020-02-03
    • 2020-05-09
    • 2022-11-11
    • 2018-09-23
    • 2021-02-24
    相关资源
    最近更新 更多