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.

  1. Followed the react native setup for Typescript from : https://reactnative.dev/docs/typescript
  2. 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;
  1. 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;
  1. 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

Most upvoted comments

@karansinghgit Ahh, I think the problem is that you’re calling useQuery before you’ve created your <ApolloProvider client={client}/> component, so useQuery can’t find any ApolloProvider above it in the component tree, and thus can’t find the client. I think you might want to move the client creation and ApolloProvider wrapping code out of your App component, so the App component can safely call useQuery. If that’s not an option, you can move the useQuery 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 nextjs page, 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 the client 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 the ExchangeRates component: https://www.apollographql.com/docs/react/get-started/#request-data

@karansinghgit Ahh, I think the problem is that you’re calling useQuery before you’ve created your <ApolloProvider client={client}/> component, so useQuery can’t find any ApolloProvider above it in the component tree, and thus can’t find the client. I think you might want to move the client creation and ApolloProvider wrapping code out of your App component, so the App component can safely call useQuery. If that’s not an option, you can move the useQuery code down into a nested component that’s rendered inside the <ApolloProvider/> component.

Thank 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:

import React from "react";
import { RootProvider } from './src/navigation';

export default function App() {

  return (
    <RootProvider />
  );

}

where RootProvider element is in another file:

import React from 'react';

import { NavigationContainer } from '@react-navigation/native';
import RootNavigator from './RootNavigator';
import { ApolloClient, InMemoryCache, ApolloProvider } from "@apollo/client";

const client = new ApolloClient({
  uri: 'MY_HASURA_INSTANCE_URL',
  headers: {
    'x-hasura-admin-secret': 'MYADMINSECRETKEY'
  },
  cache: new InMemoryCache()
});

export function Navigation() {
  return (
    <NavigationContainer>
      <RootNavigator />
    </NavigationContainer>
  );
};

export function RootProvider() {
  return (
    <ApolloProvider client={client}>
      < Navigation />
    </ApolloProvider>
  );
}

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:

  1. I am using yarn workspaces and lerna and my projects root package.json was resolving to an older version of @apollo/client even after a clean bootstrap. Setting the @apollo/client version in the root dependencies fixed this - though the next step may have made this unnecessary.
  2. Assuming other apollo packages are relying on an older @apollo/client, they may not be resolving correctly. I am using webpack, and to ensure all packages resolve to the same @apollo/client, I added an alias to my config. Something like the following in webpack.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 yarns resolution in the root package.json instead of the above two more complicated steps.

/* package.json */

	...
	"resolutions": {
		"@apollo/client": "^3.4.0-beta.19"
	},
	...

I no longer have the error and my type errors are gone.

@davidcostadev none of those

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”,

import client from './api/Apollo' // This is fine..

 <I18nextProvider i18n={i18n}>
    <ApolloProvider client={client}>

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.