Search code examples
apolloapollo-clientvue-apollo

ApolloClient: optimisticResponse becomes "undefined" during update


I'm trying to do an optimisticResponse in a mutation with ApolloClient with vue-apollo.

The mutation itself works fine - the server gets updated, and when I refresh the page, the insert has successfully appeared. However, the optimisticResponse that gets written to the query becomes "undefined" once the update() function runs for the second time, with the "real" response from the server.

My mutation code looks like this:

this.$apollo.mutate({
  mutation: UPSERT_ITEMS,
  variables: {
    todoInput: [todoInput]
  },

  update: (store, result) => {
    const upsertTodos = result.data!.upsertTodos
    const newTodo = upsertTodos.todo
    const data = store.readQuery<QueryResult>({ query: GET_PROJECTS })
    console.log("Results from the cache:", data);
    data!.rc_todos.push(newTodo)
    console.log("after that push, data looks like...", data)
    store.writeQuery({ query: GET_PROJECTS, data })

    // re-reading the query for debugging purposes:
    const sameData = store.readQuery<QueryResult>({ query: GET_PROJECTS })
    console.log("New results from the cache:", sameData)
  },
  optimisticResponse: {
    __typename: "Mutation",
    upsertTodos: {
      __typename: "InsertedTodo",
      id: 1,
      todo_id: 1,
      todo: {
        id: 1,
        label: nodeTitle,
        children: [],
        __typename: "rc_todos"
      }
    },
  },
})

Note that right now I'm calling readQuery a second time in update() for debugging purposes.

In that second call of readQuery in the first run of update() (i.e. right after inserting optimisticResponse it looks like this: enter image description here ...so everything looks fine, the fields there match the data that was already in the cache, etc.

But, when update() runs the second time (to process results from the server) our optimisticResponse is "there" but as undefined: enter image description here

This yields an error TypeError: Cannot read property '__typename' of undefined.

To be honest, I'm not sure what's supposed to be happening at this point in the lifecycle... should optimisticResult still be there? Or should it have already been removed? In either case, I'm sure it shouldn't be there and undefined since that's causing the error.


Solution

  • It turned out to be a silly mistake- the real response from the mutation the server was returning was a different shape than how it was set up in the client.

    The part I screenshotted in my question is actually the intended behavior- it sets the previously added optimisticResponse to undefined so as to remove it once the "real" data is available.