【问题标题】:Apollo Client: Upsert mutation only modifies cache on update but not on createApollo 客户端:Upsert 突变仅在更新时修改缓存,但在创建时不修改
【发布时间】:2017-05-30 15:50:52
【问题描述】:

我有一个在创建或更新时触发的 upsert 查询。在更新时,Apollo 会将结果整合到缓存中,但在创建时不会。

这里是查询:

export const UPSERT_NOTE_MUTATION = gql`
  mutation upsertNote($id: ID, $body: String) {
    upsertNote(id: $id, body: $body) {
      id
      body
    }
  }`

我的客户:

const graphqlClient = new ApolloClient({
  networkInterface,
  reduxRootSelector: 'apiStore',
  dataIdFromObject: ({ id }) => id
});

来自服务器的响应是相同的:idbody 都返回了,但 Apollo 不会自动将新 id 添加到 data 缓存对象中。

是否可以让 Apollo 自动将新对象添加到 data 而不会触发后续提取?

这是我的数据存储的样子:

更新

根据文档,updateQueries 函数应该允许我将新元素推送到我的资产列表中,而无需再次触发我的原始获取查询。

函数被执行,但函数返回的任何内容都被完全忽略,缓存没有被修改。

即使我这样做:

    updateQueries: {
      getUserAssets: (previousQueryResult, { mutationResult }) => {
        return {};
      }
    }

没有任何变化。

更新 #2

仍然无法更新我的资产列表。

updateQueries 内部,这是我的previousQueryResult 的样子:

    updateQueries: {
      getUserAssets: (previousQueryResult, { mutationResult }) => {
        return {
          assets: []
            .concat(mutationResult.data.upsertAsset)
            .concat(previousQueryResult.assets)
        }
      }
    }

但是无论我返回什么,数据存储都不会刷新:

作为参考,下面是每个 asset 的样子:

【问题讨论】:

标签: javascript react-redux apollostack react-apollo apollo-client


【解决方案1】:

您是否按照示例here 进行操作? 我会像这样在 mutate 中编写 updateQueries:

updateQueries: {
  getUserAssets: (previousQueryResult, { mutationResult }) => {
    const newAsset = mutationResult.data.upsertAsset;
    return update(prev, {
      assets: {
        $unshift: [newAsset],
      },
    });
  },  
}

或者使用对象分配而不是从 immutability-helper 更新:

updateQueries: {
  getUserAssets: (previousQueryResult, { mutationResult }) => {
    const newAsset = mutationResult.data.upsertAsset;
    return Object.assign({}, prev, {assets: [...previousQueryResult.assets, newAsset]});
  },  
}

【讨论】:

  • 感谢您的回答。我已经尝试了您的两个建议,但它们都不起作用。我也按照您之前发送的链接没有运气。发生的情况是成功发出了成功的 graphql 请求,但是在我刷新页面之前,新创建的资产不会添加到资产列表中。这绝对令人难以置信。
【解决方案2】:

正如您在更新中所述,您需要使用updateQueries 来更新与此突变相关的查询。尽管您的问题没有说明要使用突变结果更新哪种查询,但我假设您有这样的事情:

query myMadeUpQuery {
  note {
    id 
    body
  }
}

它应该返回当前系统中的笔记列表以及每个笔记的 ID 和正文。使用updateQueries,您的回调接收查询结果(即有关新插入的注释的信息)和此查询的先前结果(即注释列表),并且您的回调必须返回应分配给的新结果上面的查询。

有关类似示例,请参阅here。本质上,如果没有给定示例使用的immutability-helper,您可以编写您的updateQueries 回调如下:

updateQueries: {
  myMadeUpQuery: (previousQueryResult, { mutationResult }) => {
    return {
      note: previousQueryResult.note(mutationResult.data.upsertNode),
    };
  }
}

【讨论】:

  • 抱歉,Dhaivat 回复晚了。我只是用更新#2更新我的问题。不幸的是,仍然无法使其正常工作。
猜你喜欢
  • 2020-02-03
  • 2021-03-11
  • 2019-03-12
  • 2019-04-02
  • 2020-11-27
  • 1970-01-01
  • 2021-04-04
  • 2020-12-14
  • 2021-10-06
相关资源
最近更新 更多