I'm having trouble with GraphQL Subscriptions in React-Apollo. The issue is that when I create a subscription it gets stuck on loading forever. Despite that, the GraphQL Subscriptions work in gql-playground so it seems like a front-end issue. I've followed the documentation closely to match it, but the subscription still returns undefined in the console and is loading.
Here is how the WebSockets with Subscriptions is set up in index.js
// Link for HTTP Requests
const httpLink = new HttpLink({
uri: 'http://localhost:8080/api'
});
// Link for Websocket Links
const wsLink = new WebSocketLink({
uri: 'ws://localhost:8080/api',
options: {
reconnect: true
}
});
// Split Function takes the operation to execute, and reuturns the Websocket Link or HTTP Link depending on a boolean value
const splitLink = split(
({ query }) => {
const definition = getMainDefinition(query);
return (
definition.kind === 'OperationDefinition' &&
definition.operation === 'subscription'
);
},
wsLink,
httpLink,
);
cosnt
const client = new ApolloClient({
connectToDevTools: true,
cache: new InMemoryCache(),
link: splitLink,
})
ReactDOM.render(
<React.StrictMode>
<ApolloProvider client={client}>
<App />
</ApolloProvider>
</React.StrictMode>,
document.getElementById('root')
);
and this is the WristbandSubscriptions component I created to test the subscriptions
const WristbandSubscriptions = () => {
const NEW_WRISTBAND_ADDED = gql`
subscription {
newWristbandAdded {
id
tic
active
name
dateOfBirth
onOxygen
pregnant
child
key
department
}
}`
;
const { data, loading, error } = useSubscription(NEW_WRISTBAND_ADDED);
useEffect(()=> {
console.log(data);
},[data])
console.log(error);
console.log("Loading: " + loading);
return (
<div>
<h1>{data}</h1>
</div>
)
}