简体   繁体   中英

Apollo GraphQL failing connection

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM