Apollo客户端写入查询未更新UI [英] Apollo Client Write Query Not Updating UI

查看:168
本文介绍了Apollo客户端写入查询未更新UI的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我们正在使用Apollo Client构建一个离线的第一个React Native应用程序.当前,我正在尝试在脱机时直接更新Apollo缓存,以乐观地更新UI.由于我们处于脱机状态,因此在connect处于联机"状态之前,我们不会尝试触发该突变,但希望UI在脱机之前仍在脱机之前触发这些更改.我们正在使用来自 http:/的readQuery/writeQuery API函数/dev.apollodata.com/core/read-and-write.html#writequery-and-writefragment .并且可以查看通过Reacotron正在更新的缓存,但是,UI不会根据此缓存更新的结果进行更新.

We are building an offline first React Native Application with Apollo Client. Currently I am trying to update the Apollo Cache directly when offline to update the UI optimistically. Since we offline we do not attempt to fire the mutation until connect is "Online" but would like the UI to reflect these changes prior to the mutation being fired while still offline. We are using the readQuery / writeQuery API functions from http://dev.apollodata.com/core/read-and-write.html#writequery-and-writefragment. and are able to view the cache being updated via Reacotron, however, the UI does not update with the result of this cache update.

    const newItemQuantity = existingItemQty + 1;
    const data = this.props.client.readQuery({ query: getCart, variables: { referenceNumber: this.props.activeCartId } });
    data.cart.items[itemIndex].quantity = newItemQuantity;
    this.props.client.writeQuery({ query: getCart, data });

推荐答案

如果查看文档示例,您会发现它们以不变的方式使用数据.传递给写查询的数据属性与读取的对象不同.突变此对象不太可能受到Apollo的支持,因为如果不进行深度拷贝和比较之前/之后的数据,该对象将无法非常有效地检测到您修改了哪些属性.

If you look at the documentation examples, you will see that they use the data in an immutable way. The data attribute passed to the write query is not the same object as the one that is read. Mutating this object is unlikely to be supported by Apollo because it would not be very efficient for it to detect which attributes you modified, without doing deep copies and comparisons of data before/after.

const query = gql`
  query MyTodoAppQuery {
    todos {
      id
      text
      completed
    }
  }
`;
const data = client.readQuery({ query });
const myNewTodo = {
  id: '6',
  text: 'Start using Apollo Client.',
  completed: false,
};
client.writeQuery({
  query,
  data: {
    todos: [...data.todos, myNewTodo],
  },
});

因此,您应该尝试使用相同的代码,而不会使数据发生变异.例如,您可以使用lodash/fp中的set来帮助您

So you should try the same code without mutating the data. You can use for example set of lodash/fp to help you

const data = client.readQuery({...});
const newData = set("cart.items["+itemIndex+"].quantity",newItemQuantity,data);
this.props.client.writeQuery({ ..., data: newData });

对于更复杂的突变,建议 ImmerJS

It recommend ImmerJS for more complex mutations

这篇关于Apollo客户端写入查询未更新UI的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆