突变后如何更新阿波罗缓存(使用过滤器查询) [英] How to update apollo cache after mutation (query with filter)

查看:201
本文介绍了突变后如何更新阿波罗缓存(使用过滤器查询)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我对GraphQL很陌生.我在带有阿波罗的Vue.js项目中使用graph.cool.

I am pretty new to GraphQL. I am using graph.cool in a Vue.js project with apollo.

  • 我现在正在使用内存中的缓存.
  • 我以前有一个简单的"allPosts"查询.
  • 在创建一个新的之后,我使用了update()钩子和readQuery()+ writeQuery()

但是我希望登录的用户只能看到他们的帖子.因此,我使用过滤器修改了查询.

However I want that logged in users can only see their posts. So I modified the query with a filter.

query userStreams ($ownerId: ID!) {
  allStreams(filter: {
   owner: {
     id: $ownerId
   }
  }) {
    id
    name
    url
    progress
    duration
    watched
    owner {
      id
    }
  }
}

我的想法是,我只需要传递userid变量.但是,这是行不通的.我总是得到

My thought was, that I only need to pass in the userid variable. However this is not working. I am always getting

Error: Can't find field allStreams({"filter":{"owner":{}}}) on object (ROOT_QUERY) undefined.




this.$apollo.mutate({
      mutation: CREATE_STREAM,
      variables: {
        name,
        url,
        ownerId
      },
      update: (store, { data: { createStream } }) => {
        const data = store.readQuery({
          query: USERSTREAMS,
          variables: {
            id: ownerId
          }
        })
        data.allStreams.push(createStream)
        store.writeQuery({
          query: USER_STREAMS,
          variables: {
            id: ownerId
          },
          data
        })
      }
    })

推荐答案

使用readQuery或writeQuery时,应使用相同的变量名.因此,替换

When you use readQuery or writeQuery, you should use the same variable name. So replace

  variables: { id: ownerId }

使用

  variables: { ownerId }

此外,获取异常的原因是,如果数据不在存储区中,则readQuery会引发异常.这是在您第一次使用writeQuery(或通过其他查询获取数据)之前发生的.

Also, the reason you are getting an exception is that readQuery throws an exception if the data is not in the store. That happens before the first time you use writeQuery (or get the data with some other query).

您可以在调用此突变之前将一些默认值写入存储.

You could write some default values to the store before calling this mutation.

您还可以使用readFragment返回null而不是引发异常.但这将需要对代码进行更多更改.

You could also use readFragment that returns null instead of throwing an exception. But that would require more changes to your code.

这篇关于突变后如何更新阿波罗缓存(使用过滤器查询)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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