Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Invariant violation when using react apollo hooks alongside query components

I'm beginning our migration from Apollo Client 2.x to 3.x beta, and I'm having trouble using both the apollo hooks and the now deprecated query/mutation components.

I'm using the packages:

@apollo/client: 3.0.0-beta.4
@apollo/react-components: 3.1.3

Using the apollo hooks works fine in this case, but using the query component, I get the following error:

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

I've created a codesandbox that shows this issue here: https://codesandbox.io/s/react-example-9p9ym

I think the issue is with the source of the ApolloProvider I'm using, but not sure which package to get that from if I want to use the new beta, while still using the query components.

like image 423
Davis Mariotti Avatar asked Nov 08 '19 18:11

Davis Mariotti


1 Answers

You should import ApolloProvider from the same package as the component or hook that's using it. That's because the context provided by ApolloProvider needs to be the same as the context being used by the component or hook. if you use different packages, the context object will be different.

The react-apollo package exports all three: ApolloProvider, Query and useQuery. If you use that package, you can use the ApolloProvider with both Query and useQuery. @apollo/client, however, only exports ApolloProvider and useQuery. That's because the graphql HOC and the render prop components have been deprecated. If you insist on using both Query and useQuery, you have to import Query from another package, like @apollo/react-components and add its ApolloProvider as well:

import {
  ApolloProvider as ApolloProvider2,
  Query,
} from '@apollo/react-components'
import {
  ApolloProvider,
  ApolloClient,
  HttpLink,
  InMemoryCache,
  useQuery,
  gql,
} from '@apollo/client'

<ApolloProvider2 client={client}>
  <ApolloProvider client={client}>
    <App/>
  </ApolloProvider>
</ApolloProvider2>

Notice that you can import gql directly from apollo@client as well.

like image 141
Daniel Rearden Avatar answered Sep 23 '22 21:09

Daniel Rearden