ApolloClient GraphQL with ReactNative
To set up a simple example of using GraphQL in a React Native application, you’ll need to follow these steps:
- Set up a React Native project.
- Install the necessary dependencies for GraphQL.
- Create a basic GraphQL server (or use a public GraphQL endpoint).
- Fetch data from the GraphQL server in your React Native app.
Here’s a step-by-step guide to achieving this:
Using React Native CLI:
Install Dependencies
Install the required dependencies for GraphQL. This includes
apollo-client
, apollo-cache-inmemory
, apollo-link-http
, and react-apollo
.
npm install @apollo/client graphql
we’ll use a public GraphQL API. In this example, we’ll use the Countries GraphQL API.
URL : ‘https://countries.trevorblades.com/'
Fetch Data from the GraphQL Server
Now, let’s set up Apollo Client and fetch data from the GraphQL server in your React Native app.
import React from 'react';
import { ApolloClient, InMemoryCache, ApolloProvider, useQuery, gql } from '@apollo/client';
import { Text, View, FlatList, StyleSheet } from 'react-native';
// Initialize Apollo Client
const client = new ApolloClient({
uri: 'https://countries.trevorblades.com/',
cache: new InMemoryCache()
});
// Define the GraphQL query
const GET_COUNTRIES = gql`
{
countries {
code
name
emoji
}
}
`;
// Component to display countries
const CountriesList = () => {
const { loading, error, data } = useQuery(GET_COUNTRIES);
if (loading) return <Text>Loading...</Text>;
if (error) return <Text>Error: {error.message}</Text>;
return (
<FlatList
data={data.countries}
keyExtractor={(item) => item.code}
renderItem={({ item }) => (
<View style={styles.item}>
<Text>{item.name} {item.emoji}</Text>
</View>
)}
/>
);
};
export default function App() {
return (
<ApolloProvider client={client}>
<View style={styles.container}>
<Text style={styles.title}>Countries</Text>
<CountriesList />
</View>
</ApolloProvider>
);
}
const styles = StyleSheet.create({
container: {
flex: 1,
justifyContent: 'center',
paddingTop: 50,
paddingHorizontal: 20
},
title: {
fontSize: 22,
marginBottom: 20,
textAlign: 'center'
},
item: {
marginVertical: 10
}
});
Explanation
Apollo Client Setup: We initialize the Apollo Client with the URI of the GraphQL server and an in-memory cache.
GraphQL Query: We define a GraphQL query to fetch the list of countries, including their code, name, and emoji.
const { loading, error, data } = useQuery(GET_COUNTRIES);
useQuery
: This is a hook provided by the Apollo Client to fetch data from a GraphQL server. When you calluseQuery
, it returns an object with properties that describe the current state of the query.GET_COUNTRIES
: This is the GraphQL query that you are executing. It is usually defined using thegql
template literal tag from Apollo Client.
Destructuring the Query Result
The object returned by useQuery
includes several properties, but the most commonly used are:
loading
: A boolean indicating whether the query is currently loading (i.e., the request is in progress).error
: An object that contains error information if the query fails.data
: The actual data returned from the query if it completes successfully.
This pattern ensures that your app gracefully handles different states of the data fetching process, providing a good user experience.
CountriesList Component: We use the useQuery
hook from Apollo to fetch data based on the GET_COUNTRIES
query. If the data is loading, we show a loading text. If there’s an error, we display the error message. Once data is fetched, we display the list of countries using a FlatList
.
App Component: We wrap our main component with ApolloProvider
and pass the client to it. Inside the main view, we display a title and the CountriesList
component.
This simple example demonstrates how to integrate GraphQL into a React Native application using Apollo Client. You can extend this by adding more queries, mutations, and handling different states more gracefully.
Github link :
Thank you.
comments down for further queries, discussion and ideas.