Storing mutations for offline with optimisticResponse

I’m attempting to create an offline capable app with apollo client. I’ve had a look at the different libraries available (apollo-link-queue and apollo-link-offline) but none of these seem to work exactly how I’d want them to, so I’ve started creating my own based on inspiration from the two libraries.

I am however hitting a problem with the way optimisticResponse is currently working and was hoping someone could help me understand what’s going on.

In the client application I call the mutation and specify a new id:

await addToDoMutation({
                variables: {
                  name,
                },
                optimisticResponse: {
                  addToDo: {
                    __typename: "ToDo",
                    id: uuidv4(),
                    name: name,
                  },
                },
              });

When the app is online
Everything works perfectly, the optimisticResponse updates the UI and when the graphql mutation succeeds it updates the UI correctly and the id in the cache is replaced with the id received from the server.

When the app is offline
The ApolloLink I’ve created stores the operations, forward and observer information in a queue:

    return new Observable((observer) => {
      const attemptId = uuidv4();
      const operationEntry = { operation, forward, observer };
      
      this.queue.set(attemptId, operationEntry);
      this.updateStatus(false);

      observer.next({
        data: context.optimisticResponse,
        errors: [],
      });

      observer.complete();
    });

when the app comes back online it then calls the stored forward with the operation.

attempt.forward(attempt.operation).subscribe(attempt.observer);

This successfully calls the graphql endpoint, however the optimisticResponse is never replaced with the new data, this leaves me with the old id in the UI and two versions in the apollo cache (one with the client generated id and the other with the server response id).

Is there a reason why the optimisticResponse id is never replaced when re-running the stored mutation?

Thanks in advance.

1 Like