Could not find “client” in the context of Query or as passed props

孤人 提交于 2019-12-23 03:25:34

问题


This is how I'm trying to implement apollo graphQL in my react native application.

But with that I do get the error

Could not find "client" in the context of Query or as passed props. Wrap the root component in an <ApolloProvider>

So I thought I have done exactly this, but obviously I'm missunderstanding something.

import React, { Component } from 'react'
import { ApolloProvider, graphql } from 'react-apollo'
import { ApolloClient } from 'apollo-client'
import { createHttpLink } from 'apollo-link-http'
import { InMemoryCache } from 'apollo-cache-inmemory'
import gql from 'graphql-tag'

import Routes from './config/routes'

// Initialize the Apollo Client
const client = new ApolloClient({
  link: createHttpLink({ uri: 'http://localhost:3000' }),
  cache: new InMemoryCache()
})

// Define query types
const DATA_QUERY = gql`
  query {
    getVersion {
      version
    }
  }
`

export class App extends Component {
  render () {
    console.log(this.props)
    // ApolloProvider lets us use Apollo Client in descendant components
    return (
      <ApolloProvider client={client}>
        <Routes />
      </ApolloProvider>
    )
  }
}

// Inject query response as `this.props.data`
export default graphql(DATA_QUERY)(App)

回答1:


The <ApolloProvider> does not wrap the graphql(DATA_QUERY) application as it is inside that component. Something like this should work: (though you might want to choose a different name)

const ApolloRoutes = graphql(DATA_QUERY)(Routes);

export default class App extends Component {
  render () {
    console.log(this.props)
    // ApolloProvider lets us use Apollo Client in descendant components
    return (
      <ApolloProvider client={client}>
        <ApolloRoutes />
      </ApolloProvider>
    )
  }
}



回答2:


I came across this question trying to find a solution to the same issue after started using @apollo/react-hooks. As the formulation of error is the same, I will still provide my answer in case it helps somebody.

The error was a lack of ApolloHooksProvider around the content. I fixed it with changing this

<ApolloProvider client={client}>
    <Content />
</ApolloProvider>

to this

import { ApolloProvider as ApolloHooksProvider } from '@apollo/react-hooks'

<ApolloProvider client={client}>
    <ApolloHooksProvider client={client}>
        <Content />
    </ApolloHooksProvider>
</ApolloProvider>


来源:https://stackoverflow.com/questions/49847145/could-not-find-client-in-the-context-of-query-or-as-passed-props

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!