Apollo's subscribeToMore is the wrong abstraction

I learned that Apollo has a subscribeToMore function for GraphQL queries. It can be used to make a subscription for real-time updates for the items returned by the query.

An example from the documentation:

const { subscribeToMore, ...result } = useQuery(
  COMMENTS_QUERY,
  { variables: { postID: params.postID } }
);
subscribeToMore({
  document: COMMENTS_SUBSCRIPTION,
  variables: { postID: params.postID },
  updateQuery: (prev, { subscriptionData }) => {
    // ...
  }
})

It's nice to have an abstraction that makes working with subscriptions easier, but this is exactly the opposite of what you want.

When you use the subscribeToMore then you'll have a query and then open a subscription. This creates a temporary dead zone: if an item is added between the query and the subscription then it will be missing from the client.

The proper way is to subscribe first and then query. This way all items are guaranteed to be received by the client.

September 15, 2024

Free PDF guide

Sign up to our newsletter and download the "How Cognito User Pools work" guide.