How to Create Subscriptions in Apollo GraphQL
GraphQL and Websockets
Hey, guys! In this article, we are going to talk about using subscriptions in an Apollo-GraphQL client. Subscriptions are generally used to update the client in real-time rather than requesting the same GET call over and over again.
To implement a subscription in a React app, we have to complete these easy steps.
Install the Required Packages
npm install --save @apollo/react-hooks apollo-link apollo-link-http apollo-link-ws apollo-utilities subscriptions-transport-ws apollo-cache-inmemory apollo-client graphql
Configure a Websocket Link
You need to configure a WebSocket link that listens to the server for changes. A socket connection is way better than calling a query repeatedly. A WebSocket connection generally starts withwss://
(WebSocket Secure).
To configure a socket connection, refer to the code below:
Configure an HTTP Link
You also need to configure an HTTP/HTTPS link for queries and mutations.
To configure an HTTP connection, refer to the code below:
import { HttpLink } from "apollo-link-http";const httpLink = new HttpLink({
uri: 'http://localhost:8000/graphql'
});
Condition to Distinguish Query and Mutation to a Subscription
Subscriptions can only be used in Websocket connections, whereas queries and mutations can only be used over HTTP/HTTPS connections.
So while calling an API, we need to distinguish subscriptions from queries and mutations so that we can choose which URL to hit for that particular request.
split()
in apollo-link
will decide which connection to use based on the given condition. split()
accepts three arguments: a function that returns a boolean value and two connections. If the condition is true, then the first connection. Otherwise, the second connection is chosen.
To distinguish query and mutation to a subscription, refer to the code below:
Configure the Apollo Client
Now apply the connections and condition above and create an Apollo client. Pass the created client as a prop to ApolloProvider
in the index.js
file.
The complete index.js
will look like this:
Implementing useSubscription() in a Component
Now that the configuration is done, we can see how to use subscriptions in a React component:
That’s all, folks! Now we can work with subscriptions in GraphQL seamlessly.