3

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>
  )

}
SpikeThea
  • 340
  • 1
  • 3
  • 13
  • did you ever come up with a solution? – Jaggler3 Jul 19 '21 at 17:29
  • 1
    This isn't an answer to this question, but for anyone who gets here trying to figure out why their publish/subscribe is working perfectly _except_ actually receiving the data on the front end, check your apollo server code to make sure that the PubSub instance doing the publishing is the same as the one in the resolver. E.g: `pubsub.publish("WTF", { arrg: i });` and `{ Subscription: { subName: { subscribe: () => pubsub.asyncIterator(["WTF"]), }, }, };` have to use the same `pubsub` variable. Mine was in different files, and I instantiated it in each. That does not work. – ClubbedAce Jan 25 '22 at 15:21

0 Answers0