Search code examples
reactjsreact-nativegraphqlapollo

Unhandled GraphQL subscription error ReferenceError: document is not defined


I'm trying to setup a subscription with my React Native app and Rails Graphql server but I get the following error mess

Unhandled GraphQL subscription error ReferenceError: document is not defined

I'm suspecting one of the library that I use is using document but not sure which one and the exemple I followed was a setup for a React app instead of React Native.

I followed this guide: https://haughtcodeworks.com/blog/software-development/graphql-rails-react-standalone/

Here is my app.js setup

...

const httpLink = createHttpLink({
  uri: `${global.URL}/graphql`,
})

const cable = ActionCable.createConsumer('ws://localhost:3000/cable')

const hasSubscriptionOperation = ({ query: { definitions } }) => {
  return definitions.some(
    ({ kind, operation }) => kind === 'OperationDefinition' && operation === 'subscription',
  )
}

const link = ApolloLink.split(
  hasSubscriptionOperation,
  new ActionCableLink({cable}),
  httpLink
)
const client = new ApolloClient({
  link: link,
  cache: new InMemoryCache()
})

return (
  <ApolloProvider client={client}>
    <Root />
  </ApolloProvider>
)

I'm open to sharing more of my code but since I'm not sure where the error could come from I would need some guidance first.


Solution

  • As Ben mentioned the tutorial is for React and not React Native, however, it does use Apollo, and for that reason I managed to make it work by instead of using the _subscribeToNewLinks method, I used the Apollo useSubscription hook and it worked! However, I'm still having issue with the channel transmission not working every time.

    const { data: subscriptionData, _error, _loading } = 
      useSubscription(NEW_LINKS, {
      shouldResubscribe: true,
      onSubscriptionData: () => refetch()
    })