How to update apollo cache after mutation (query with filter)

一曲冷凌霜 提交于 2020-01-24 22:20:26

问题


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

  • I am using right now the in-memory cache.
  • I had previously a simple 'allPosts' query.
  • And after creating a new one, I used the update() hook and 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
    }
  }
}

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

回答1:


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

  variables: { id: ownerId }

With

  variables: { ownerId }

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.

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



来源:https://stackoverflow.com/questions/48986269/how-to-update-apollo-cache-after-mutation-query-with-filter

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!