Unhandled GraphQL subscription error ReferenceError: document is not defined

Unhandled GraphQL subscription error ReferenceError: document is not defined

我正在尝试使用我的 React Native 应用程序和 Rails Graphql 服务器设置订阅,但出现以下错误

Unhandled GraphQL subscription error ReferenceError: document is not defined

我怀疑我使用的库之一正在使用文档,但不确定我遵循的是哪个库和示例是 React 应用程序而不是 React Native 的设置。

我遵循了这个指南:https://haughtcodeworks.com/blog/software-development/graphql-rails-react-standalone/

这是我的 app.js 设置

...

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

我愿意分享更多我的代码,但由于我不确定错误可能来自何处,因此我首先需要一些指导。

您显示的指南不是针对 react native,而是针对 react AND react-dom。我想您已经知道这一点,这就是您删除 document.getElementById('root') 的原因,但您不知道 graphql-ruby-client 出于某种原因需要 DOM。它依赖于 document,而在 react native 中,全局范围内没有 document 对象。这仅在浏览器中可用。

我建议使用不同的 graphQL 客户端,例如 Apollo Client

正如 Ben 所提到的,该教程适用于 React 而不是 React Native,但是,它确实使用了 Apollo,因此我设法通过使用 _subscribeToNewLinks 方法,我使用了 Apollo useSubscription 钩子,它成功了!但是,我仍然遇到频道传输每次都无法正常工作的问题。

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