我有一个非常简单的本地响应设置,我试图通过Apollo连接到Graphql服务器。
这是我修改过的唯一文件(在CRNA之后),如下所示:
App.tsx
import React from 'react';
import { StyleSheet, ScrollView, Text, FlatList } from 'react-native';
import { ApolloProvider, useQuery } from '@apollo/client';
import client from './apollo';
import gql from 'graphql-tag';
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 = () => {
const { data, error, loading } = useQuery(
FETCH_TODOS,
);
return (
<ApolloProvider client={client}>
<ScrollView
style={styles.scrollView}>
<FlatList
data={data.todos}
renderItem={({ item }: any) => <Text>{item}</Text>}
keyExtractor={(item) => item.id.toString()}
/>
</ScrollView>
</ApolloProvider>
);
};
const styles = StyleSheet.create({
scrollView: {
backgroundColor: "white",
}
});
export default App;
makeApolloClient文件是这样的:
apollo.ts
import {
ApolloClient,
InMemoryCache,
NormalizedCacheObject,
createHttpLink
} from '@apollo/client'
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}`
}
});
const cache = new InMemoryCache()
const client = new ApolloClient({
link: link as any,
cache
});
return client;
}
const client = makeApolloClient({ token: "eyJhbGciOiJSUzI1NiIsInR5cCI6IkpXVCIsImtpZCI6Ik9FWTJSVGM1UlVOR05qSXhSRUV5TURJNFFUWXdNekZETWtReU1EQXdSVUV4UVVRM05EazFNQSJ9" });
export default client;
在运行npx react-native run-android
时,这是我得到的错误:
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.
由于我已经包装了ApolloProvider拥有的唯一组件,因此无法弄清问题所在。