How to detect disconnect and reconnect for subscription(websocket) in apollo client

I am building a chat service and I want to handle the cases when the subscription(websocket) connection is disconnected. Apollo client is configured like bellow. I removed unnecessary code like cache, authLink etc.

How do I do this with react, apollo client? If its disconnected, I would like to show that to the chat page and when the user reconnects, I would like to fetch all the missed chat messages. This is why I need to know the disconnect, connect events

Below are the relevant packages used in this app:

"@apollo/client": "^3.3.7",
"subscriptions-transport-ws": "^0.9.18",
"react": "^17.0.1"
const httpLink = new BatchHttpLink({ uri: config.API_URL })
const wsLink = new WebSocketLink({
  uri: config.WS_URL,
  options: {
    reconnect: true,
    connectionParams:{       
      authToken: accessToken,
    },
  },
})

const splitLink = split(
  ({ query }) => {
    const definition = getMainDefinition(query) 
    return definition.kind === 'OperationDefinition' && definition.operation === 'subscription'
  },
  wsLink,
  httpLink
)
const client = new ApolloClient({
  cache,
  link: from([new SentryLink(), authLink, errorLink, splitLink]),
})

Source: ReactJs

LEAVE A COMMENT