Apollo Elements Apollo Elements Guides API Blog Toggle darkmode

Usage: Subscriptions

Subscription components fetch data in real time via GraphQL subscriptions, which usually use websockets under the hood.

Example: Chat App

A chat app queries for a list of messages, then initiates a subscription for all incoming messages. When a new message comes in, we want to notify the users, as well as add the message to the bottom of the existing on-screen list.

Consider this query and subscription:

query MessagesQuery {
  messages {
    date
    message
    user
  }
}
subscription MessageSentSubscription {
  messageSent {
    date
    message
    user
  }
}

Let's define a component which performs the following tasks:

  1. queries for messages
  2. subscribes to any new messages
  3. when new messages arrive, integrate them with the cached messages from the query.

We'll accomplish this by calling subscribeToMore on our element once it's connected to the DOM, passing in an updateQuery function to define the merge for new data:

ApolloSubscriptionController

The first approach of calling subscribeToMore suits our requirement of updating the list of messages, but we still have to notify our users. Let's use a subscription controller and run our notification side effect using its lifecycle events.

Subscription Component

We could create on a separate <chat-subscription> component to handle fetching the subscription side. See the HTML example in the previous section for an example of listening for the subscription's lifecycle events to update the query

Next Steps

See this simple chat-app demo which demonstrates building custom elements which subscribe to a GraphQL server over websockets: #leeway

Dive into the ApolloSubscription API and component lifecycle or continue on to the managing local state guide.