Search code examples
reactjsgraphqlapollo-clientgraphql-subscriptions

Add subscription to specific route in apollo client GraphQL React app


I'm looking for a solution where I can add the subscription to a specific route instead of binding the subscription globally when the app start.

I know the subscription can be acheived with following code

const wsLink = new WebSocketLink({
  uri: `ws://localhost:4000`,
  options: {
    reconnect: true,
    connectionParams: {
      authToken: localStorage.getItem(AUTH_TOKEN),
    }
  }
})

const link = split(
  ({ query }) => {
    const { kind, operation } = getMainDefinition(query)
    return kind === 'OperationDefinition' && operation === 'subscription'
  },
  wsLink,
  authLink.concat(httpLink)
)

const client = new ApolloClient({
  link,
  cache: new InMemoryCache()
})

But if I add this, the subscription is directly active upon page load irrespective of what page I'm on.

Is there any solution where I can bind the subscription on a specific page instead of having it binded globally.


Solution

  • If you are passing token in a query parameter and want to reconnect to the link all you need to do is update the link back by reassigning it

    wsLink.subscriptionClient.url = `${GraphQLSocketURL}/query?authorization=${newAccessToken}`;
    

    And if you want to establish connection when the page is loaded all you need to do is set lazy flag to true

    const wsLink = new WebSocketLink({
      uri: `${GraphQLSocketURL}/query?authorization=${accessToken}`,
      options: {
        reconnect: true,
        reconnectionAttempts: 10,
        lazy: true,
      },
    });