Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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
        })
      }
    })
like image 886
Jakub Juszczak Avatar asked Mar 06 '26 11:03

Jakub Juszczak


1 Answers

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.

like image 109
Tal Z Avatar answered Mar 08 '26 19:03

Tal Z



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!