Ad
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.
Ad
Answer
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,
},
});
Ad
source: stackoverflow.com
Related Questions
- → Import statement and Babel
- → should I choose reactjs+f7 or f7+vue.js?
- → Uncaught TypeError: Cannot read property '__SECRET_DOM_DO_NOT_USE_OR_YOU_WILL_BE_FIRED' of undefined
- → .tsx webpack compile fails: Unexpected token <
- → React-router: Passing props to children
- → ListView.DataSource looping data for React Native
- → React Native with visual studio 2015 IDE
- → Can't test submit handler in React component
- → React + Flux - How to avoid global variable
- → Webpack, React & Babel, not rendering DOM
- → How do I determine if a new ReactJS session and/or Browser session has started?
- → Alt @decorators in React-Native
- → How to dynamically add class to parent div of focused input field?
Ad