Apollo GraphQL failing connection

203 Views Asked by At

My root component is already wrapped with an ApolloProvider tag, but the error message tells me it is not.

Error Message

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.

This error is located at:
    in App (created by ExpoRoot)

Problem is my root component is already wrapped with an ApolloProvider tag

React Native Code

IMPORT statements

import {
  ApolloClient,
  InMemoryCache,
  useQuery,
  ApolloProvider,
  gql,
} from "@apollo/client";

CONNECTION WITH GraphQL

const client = new ApolloClient({
  uri: "https://www.outvite.me/gql/gql",
  cache: new InMemoryCache(),
  defaultOptions: { watchQuery: { fetchPolicy: 'cache-and-network' } },
})

TEST QUERY

const USER_QUERY = gql`
  query USER {
    users {
      nodes {
        edge {
          username
        }
      }
    }
  }
`

DEFAULT APP

THIS IS WHERE THE ERROR IS BEING THROWN

const { data, loading } = useQuery(USER_QUERY) is the line that traceback shows

export default function App() {
    const { data, loading } = useQuery(USER_QUERY)
    return (
        <ApolloProvider client={client}>
           <View>
             <Text style={styles.text}>Open</Text>
             <Text style={styles.text}>Another text</Text>
           </View>
           <Button title="Toggle Sidebar" onPress={() => toggleSidebarView()} />
           <Button title="Change theme" onPress={() => toggleColorTheme()} />
        </ApolloProvider>
    );
}
1

There are 1 best solutions below

0
Tyler On BEST ANSWER

If I'm not mistaken, the useQuery hook only works if you're in a component that is already wrapped in the ApolloProvider so you probably want to do something like this

export default function MainApp() {
    const { data, loading } = useQuery(USER_QUERY)
    return (
      <View>
        ... use 'data' in here somewhere...
      </View>
    );
}

and then the top-level App component would look like

export default function App() {
    return (
      <ApolloProvider client={client}>
        <MainApp />
      </ApolloProvider>
    );
}