Skip to content
This repository has been archived by the owner on Apr 13, 2023. It is now read-only.

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

Open
jfarris587 opened this issue Jun 15, 2020 · 0 comments

Comments

@jfarris587
Copy link

jfarris587 commented Jun 15, 2020

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

Sign up for free to subscribe to this conversation on GitHub. Already have an account? Sign in.
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant