Apollo Client Write Query Not Updating UI

前端 未结 2 1827
悲&欢浪女
悲&欢浪女 2021-01-05 09:13

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 optimis

2条回答
  •  一整个雨季
    2021-01-05 10:02

    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],
      },
    });
    

    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 });
    

    It recommend ImmerJS for more complex mutations

提交回复
热议问题