Apollo客户端:Upsert突变仅在更新时修改缓存,但在创建时不修改

时间:2017-01-15 20:00:24

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

我有一个在创建或更新时触发的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而不会触发后续提取?

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

enter image description here

更新

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

该函数被执行但该函数返回的内容将被完全忽略,并且不会修改缓存。

即使我做了这样的事情:

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

没有任何改变。

更新#2

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

updateQueries内,这是previousQueryResult的样子:

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

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

enter image description here

供参考,以下是每个asset的样子:

enter image description here

2 个答案:

答案 0 :(得分: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]});
  },  
}

答案 1 :(得分:0)

正如您在更新中所述,您需要使用updateQueries来更新与此突变相关的查询。虽然你的问题没有说明使用变异的结果更新哪种查询,但我认为你有类似的东西:

query myMadeUpQuery {
  note {
    id 
    body
  }
}

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

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

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