【问题标题】:Unhandled GraphQL subscription error ReferenceError: document is not defined未处理的 GraphQL 订阅错误 ReferenceError: document is not defined
【发布时间】:2020-03-01 06:30:00
【问题描述】:

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

未处理的 GraphQL 订阅错误 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>
)

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

【问题讨论】:

  • 错误堆栈跟踪的屏幕截图将有助于更多地找到根本原因

标签: reactjs react-native graphql apollo


【解决方案1】:

您展示的指南不是针对 react native,而只是针对 react AND react-dom。我想你已经知道这就是为什么你删除了document.getElementById('root'),但你不知道graphql-ruby-client,出于某种原因需要DOM。它依赖于文档,并且在本机反应中,全局范围内没有 document 对象。这仅在浏览器中可用。

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

【讨论】:

    【解决方案2】:

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

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

    【讨论】:

      猜你喜欢
      • 2020-12-09
      • 2012-06-07
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-08-08
      • 1970-01-01
      • 2022-12-29
      相关资源
      最近更新 更多