Skip to content

Instantly share code, notes, and snippets.

@vincicat

vincicat/App.js Secret

Created March 10, 2023 21:35
Show Gist options
  • Save vincicat/faf1522d12df39c3019e7f6142b1db1b to your computer and use it in GitHub Desktop.
Save vincicat/faf1522d12df39c3019e7f6142b1db1b to your computer and use it in GitHub Desktop.
Single-File JavaScript Example: Apollo in React Native
/* eslint-disable react-native/no-inline-styles */
// the minimal example extracted from https://github.com/GraphQLGuide/guide-react-native
import React from 'react';
import {
Text,
FlatList,
View,
ActivityIndicator,
SafeAreaView,
} from 'react-native';
import {
ApolloClient,
InMemoryCache,
ApolloProvider,
gql,
useQuery,
} from '@apollo/client'; // peer dependency: graphql
// Query
const CHAPTERS_QUERY = gql`
query Chapters {
chapters {
id
number
title
}
}
`;
// Screen(s)
function HomeScreen() {
// You can put the gql query in here if you hate to declare more variable
const {data, loading} = useQuery(CHAPTERS_QUERY);
if (loading) {
return <ActivityIndicator />;
}
return (
<FlatList
data={data.chapters}
renderItem={({item}) => {
const {number, title} = item;
return (
<View style={{padding: 10}}>
<Text>
{number !== null && `${number + 1}. `}
{title}
</Text>
</View>
);
}}
keyExtractor={item => item.id.toString()}
ItemSeparatorComponent={() => (
<View style={{borderBottomWidth: 1, borderBottomColor: '#bbb'}} />
)}
/>
);
}
// client setup
const cache = new InMemoryCache();
const client = new ApolloClient({
uri: 'https://api.graphql.guide/graphql',
cache,
defaultOptions: {watchQuery: {fetchPolicy: 'cache-and-network'}},
});
export default function App() {
return (
<ApolloProvider client={client}>
<SafeAreaView>
<HomeScreen />
</SafeAreaView>
</ApolloProvider>
);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment