apollographql / react-apollo

:recycle: React integration for Apollo Client
https://www.apollographql.com/docs/react/
MIT License
6.85k stars 790 forks source link

Creating npm module that uses <Query> component without instantiating <ApolloProvider> in the module #4024

Open jfarris587 opened 4 years ago

jfarris587 commented 4 years ago

Attempting to create a npm library of Apollo components. The component library would have React components that use <Query> component to generate the QueryResult. However, the is not set in the npm module itself, but at a higher level. See the example below of how it is envisioned...

The problem is that, for it to work properly, has to be defined from within the npm module itself. If I leave it out, and depend on it being wrapped in App.tsx then the below error occurs. Is it not possible to make npm library of Apollo components while defining the Provider at a higher level?

error

Could not find "client" in the context or passed in as an option. Wrap the root component in an <ApolloProvider>, or pass an ApolloClient instance in via options.

Example React App:

index.tsx

import React from 'react'
import ReactDOM from 'react-dom'
import App from './App'

import { ApolloClient } from 'apollo-client'
import { InMemoryCache } from 'apollo-cache-inmemory'
import { ApolloProvider } from 'react-apollo'
import { HttpLink } from 'apollo-link-http'

const link = new HttpLink({
  uri:  [hidden],
  headers: {
    Authorization: `Bearer [hidden]`
  },
  credentials: 'same-origin'
})

const client = new ApolloClient({
  link: link,
  cache: new InMemoryCache()
})

const ApolloApp = () => (
  <ApolloProvider client={client}>
    <App />
  </ApolloProvider>
)

ReactDOM.render(<ApolloApp />, document.getElementById('root'))

App.tsx

import React from 'react'

import { HeaderWithQuery } from 'my-test-components'
import gql from 'graphql-tag'

const App = () => {
  return (
    <div>
      <HeaderWithQuery></HeaderWithQuery>
    </div>
  )
}

const query = gql`
  query Header {
    [graphql here]
  }
`

export default App

NPM Module File

imported npm module file: Header.ts

Notice how is not defined. I don't want the connection defined here. I want it instantiated in the source code, not the module.

export const HeaderWithQuery = () => {
  return (
    <Query
      query={query}
    >
      {({ loading, error, data }: any) => {
        console.log(data)
        return <h1>hello world</h1>
      }}
    </Query>
  )
}