apollo-client: 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.
Intended outcome:
I was hoping to connect with the Hasura server using Apollo Actual outcome:
Got the error response:
Invariant Violation: 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.
How to reproduce the issue:
I have a very simple setup.
- Followed the react native setup for Typescript from : https://reactnative.dev/docs/typescript
- Modified
App.tsx
to:
import React from 'react';
import { StyleSheet, ScrollView, Text, FlatList } from 'react-native';
import { ApolloProvider, ApolloClient, useQuery } from '@apollo/client';
import makeApolloClient from './apollo';
import gql from 'graphql-tag';
// import { useQuery } from '@apollo/react-hooks';
export const FETCH_TODOS = gql`
query {
todos (
order_by: {
created_at: desc
},
where: { is_public: { _eq: false} }
) {
id
title
is_completed
created_at
is_public
user {
name
}
}
}
`;
const App: () => React.ReactNode = () => {
let [client, setClient] = React.useState({} as ApolloClient<any>);
client = makeApolloClient("eyJhbGciOiJSUzI1NiIsInR5cCI6IkpXVCIsImtpZCI6Ik9FWTJSVGM1UlVOR05qSXhSRUV5TURJNFFUWXdNekZETWtReU1EQXdSVUV4UVVRM05EazFNQSJ9");
setClient(client);
const { data, error, loading } = useQuery(
FETCH_TODOS,
);
return (
<ApolloProvider client={client}>
<ScrollView
contentInsetAdjustmentBehavior="automatic"
style={styles.scrollView}>
<FlatList
data={data.todos}
renderItem={({ item }) => <Text>{item}</Text>}
keyExtractor={(item) => item.id.toString()}
/>
</ScrollView>
</ApolloProvider>
);
};
const styles = StyleSheet.create({
scrollView: {
backgroundColor: "white",
}
});
export default App;
- Apollo function import from
apollo.ts
:
import {
ApolloClient,
InMemoryCache,
NormalizedCacheObject,
createHttpLink
} from '@apollo/client'
export function makeApolloClient({ token }: any): ApolloClient<NormalizedCacheObject> {
// create an apollo link instance, a network interface for apollo client
const link = createHttpLink({
uri: `https://hasura.io/learn/graphql`,
headers: {
Authorization: `Bearer ${token}`
}
});
// create an inmemory cache instance for caching graphql data
const cache = new InMemoryCache()
// instantiate apollo client with apollo link instance and cache instance
const client = new ApolloClient({
link: link as any,
cache
});
return client;
}
export default makeApolloClient;
- ran
npx react-native run-android
.
Versions
System:
OS: Windows 10 10.0.19042
Binaries:
Node: 12.18.2 - C:\Program Files\nodejs\node.EXE
Yarn: 1.22.5 - C:\Program Files (x86)\Yarn\bin\yarn.CMD
npm: 6.14.5 - C:\Program Files\nodejs\npm.CMD
Browsers:
Chrome: 86.0.4240.111
Edge: Spartan (44.19041.423.0), Chromium (86.0.622.51), ChromiumDev (88.0.673.0)
npmPackages:
@apollo/client: 3.2.0 => 3.2.0
I actually downgraded @apollo/client from 3.2.4 to test this. Both of the versions did not work.
About this issue
- Original URL
- State: closed
- Created 4 years ago
- Reactions: 8
- Comments: 28 (4 by maintainers)
Commits related to this issue
- ApolloProvider issue, refer https://github.com/apollographql/apollo-client/issues/7242 — committed to Puzzoh/puzzoh-mobile-v1 by mphung1 a year ago
@karansinghgit Ahh, I think the problem is that you’re calling
useQuery
before you’ve created your<ApolloProvider client={client}/>
component, souseQuery
can’t find anyApolloProvider
above it in the component tree, and thus can’t find theclient
. I think you might want to move the client creation andApolloProvider
wrapping code out of yourApp
component, so theApp
component can safely calluseQuery
. If that’s not an option, you can move theuseQuery
code down into a nested component that’s rendered inside the<ApolloProvider/>
component.After long hours i figured out this nonesense https://github.com/apollographql/apollo-client/issues/7112#issuecomment-702884623 works. This project starting to become ridiculous. @apollo/client@^3.4.0-beta.20
I am also encountering this issue.
In my case, it is not due to the use of outdated libraries (all of my imports are from
@apollo/client@latest
).If I use a hook (e.g.
useMutation
) in a nextjspage
, everything works fine.If, however, I move that
useMutation()
call to one of that page’s children, I get the referenced error.I don’t know how react context plays with nextjs, and nextjs’ nightmare of a routing system probably messes with things, but my understanding is that
ApolloProvider
should provide theclient
to any children components (without HOCs, which aren’t exactly best-practices any longer and add extra boilerplate, something Apollo has enough of already cough list insert cache updates cough), so I’m not sure why it’s not working. Obviously, calling all my Apollo hooks in root page components isn’t a viable long-term solution, so I hope someone who understands the intricacies of how these two libraries are meant to interact can shine some light onto the situation.Today I also got into this trap, though I “thought” that I did follow their tutorial very carefully 😃)
But the trick is, you need to use the
useQuery
in a child component of where you wrap with<ApolloProvider client={client}>
In their Quick Started guide, they have to use
useQuery
inside of theExchangeRates
component: https://www.apollographql.com/docs/react/get-started/#request-dataThank you for sharing this! I used this approach and resolved the issue 👍
@An0r4k the suggestion provided by @benjamn worked for me. My current
App.tsx
looks like:where
RootProvider
element is in another file:It’s possible the error is related to package version mismatches.
I decided to try
@apollo/client@^3.4.0-beta.19
and I ran into this issue. In my case I think I had two issues:lerna
and my projects rootpackage.json
was resolving to an older version of@apollo/client
even after a clean bootstrap. Setting the@apollo/client
version in the rootdependencies
fixed this - though the next step may have made this unnecessary.apollo
packages are relying on an older@apollo/client
, they may not be resolving correctly.I am usingwebpack
, and to ensure all packages resolve to the same@apollo/client
, I added an alias to my config. Something like the following inwebpack.config.js
:webpack.resolve.alias: { ‘@apollo/client’: path.resolve(__dirname, ‘node_modules’, ‘@apollo’, ‘client’) }I no longer have the error.EDIT:
Thanks to this comment on a related type issue I was having, I instead opted to use yarnsresolution
in the rootpackage.json
instead of the above two more complicated steps.I no longer have the error and my type errors are gone.
@davidcostadev none of those
@stevematdavies are you using @apollo/react-components, @apollo/react-hoc, @apollo/react-ssr, @apollo/react-testing, @apollo/react-hooks?
Exactly the same problem, just happened with no updates or changes. First disappears when the cache is cleaned but then on next page render its back.
Using “react-apollo”: “^2.5.2”,
client is a successful import and is there, no lint errors no runtime errors, just this, and its turning out to be pretty serious issue
Could not find "client" in the context of ApolloConsumer. Wrap the root component in an <ApolloProvider>
There is no option to up or downgrade for various reasons.