如何从变异查询更新 Apollo 数据 store/cache,更新选项似乎没有触发

How do I update the Apollo data store/cache from a mutation query, the update option doesn't seem to trigger

我的 React Native 应用程序中有一个高阶组件可以检索配置文件。当我调用 "add follower" 突变时,我希望它更新配置文件以反映其关注者集合中的新关注者。如何手动触发对商店的更新。我可以重新获取整个配置文件对象,但更愿意在没有网络重新获取的情况下只执行插入客户端。目前,当我触发突变时,配置文件不会反映屏幕上的变化。

看起来我应该使用 update 选项,但它似乎对我命名的突变不起作用。 http://dev.apollodata.com/react/api-mutations.html#graphql-mutation-options-update

const getUserQuery = gql`
 query getUserQuery($userId:ID!) {
    User(id:$userId) {
      id
      username
      headline
      photo
      followers {
        id
        username
        thumbnail
      }
    }
 }
`;
...

const followUserMutation = gql`
  mutation followUser($followingUserId: ID!, $followersUserId: ID!) {
    addToUserFollowing(followingUserId: $followingUserId, followersUserId: $followersUserId) {
      followersUser {
        id
        username
        thumbnail
      }
    }
  }`;
...

@graphql(getUserQuery)
@graphql(followUserMutation, { name: 'follow' })
@graphql(unfollowUserMutation, { name: 'unfollow' })
export default class MyProfileScreen extends Component Profile

...

  this.props.follow({
    variables,
    update: (store, { data: { followersUser } }) => {
      //this update never seems to get called
      console.log('this never triggers here');
      const newData = store.readQuery({ getUserQuery });
      newData.followers.push(followersUser);
      store.writeQuery({ getUserQuery, newData });
    },
  });

编辑:刚刚意识到您需要将更新添加到突变的 graphql 定义中。

编辑 2:@MonkeyBonkey 发现您必须在读取查询函数中添加变量

@graphql(getUserQuery)
@graphql(followUserMutation, {
  name: 'follow',
  options: {
    update: (store, { data: { followersUser } }) => {

       console.log('this never triggers here');
       const newData = store.readQuery({query:getUserQuery, variables});
       newData.followers.push(followersUser);
       store.writeQuery({ getUserQuery, newData });
     }
  },
});
@graphql(unfollowUserMutation, {
  name: 'unfollow'
})
export default class MyProfileScreen extends Component Profile

  ...

  this.props.follow({
      variables: { .... },
    );

我建议您使用 updateQueries 功能更新商店 link

例如,参见此

您可以使用 compose 将突变添加到组件中。在 mutation 中你不需要调用 client.mutate。您只需在关注用户点击时调用突变。

也可以让 apollo 为您处理更新。如果稍微更改突变响应,则将以下用户添加到关注用户并添加 dataIdFromObject 功能。 link