突变后如何更新阿波罗缓存(使用过滤器查询) [英] How to update apollo cache after mutation (query with filter)
问题描述
我对 GraphQL 还很陌生.我在带有 apollo 的 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.
您还可以使用返回 null 而不是抛出异常的 readFragment.但这需要对您的代码进行更多更改.
You could also use readFragment that returns null instead of throwing an exception. But that would require more changes to your code.
这篇关于突变后如何更新阿波罗缓存(使用过滤器查询)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!