Skip to main content

How to use GraphQL in React Native

How do you work with GraphQL in React Native? Here's a step-by-step tutorial to get you started!


In this article, let's look at how to setup, integrate and fetch data from a GraphQL API in a React Native app.

Before we begin, here's some things you should know:

  • Any code editor
  • Basic React Native knowledge (i.e. FlatList, Text, View, etc.)
  • Basic GraphQL knowledge (i.e. what it is, how it works)

    If you need a refresher on GraphQL, please read my Introduction to GraphQL article

If you haven't already, install Expo CLI.

npm install -g expo-cli

Then, create a new expo project using the following command:

expo init myApp

Now we install these 2 dependencies by running:

npm install @apollo/client graphql
  • apollo/client: connects client to a GraphQL API
  • graphql: provides GraphQL capabilities

To start the app, run:

expo start

To integrate Apollo Client in our React Native app, we need to first import and initialize a new ApolloClient in our App component.

import { ApolloClient, InMemoryCache, ApolloProvider } from '@apollo/client';

// Initialize Apollo Client
const client = new ApolloClient({
  uri: 'https://countries.trevorblades.com/graphql',
  cache: new InMemoryCache()
});

The uri refers to the GraphQL API endpoint that we will fetch data from. In this tutorial, I will be fetching some country data from the url: https://countries.trevorblades.com/graphql.API.png

This is a free-to-use GraphQL API for beginners to test and use. It even comes with an explorer to show you how to construct the queries and see the API response. We will get back to this API soon.

So let's continue by wrapping ApolloProvider around the App component and pass client as a prop.

export default function App() {
  return (
    <ApolloProvider client={client}>
    <View style={styles.container}>
      <Text style={styles.title}>My Countries App</Text>
    </View>
    </ApolloProvider>
  );
}

Now let's create a simple HomeScreen component to display a list of continent names that we will fetch from the API.

In the root directory, we can create a src/HomeScreen.js component as shown below:

import { Text, FlatList, Pressable } from 'react-native'

export default function HomeScreen() {
  return (
    <Text>This is my Home Screen.</Text>
  );
}

Don't forget to import our HomeScreen component in our App.js like so:

import HomeScreen from './src/HomeScreen';

export default function App() {
  return (
    <ApolloProvider client={client}>
    <View style={styles.container}>
      <Text style={styles.title}>My Countries App</Text>
      <HomeScreen/> {/*import here*/}
    </View>
    </ApolloProvider>
  );
}

Now let's add our GraphQL query to fetch continent names. If you're unsure how to write a GraphQL query, this countries API has a playground to test and help you write the queries.

For example, if we want to fetch a list of continent names, we can simply select the field name on the left panel. The query will automatically be shown in the middle panel.

query.PNG

Finally, running the query by clicking the blue button in the middle panel will allow you to view the results of the query, as shown in the screenshot above.

So let's start with creating a folder in src called gql/Query.js, where we will write all our GraphQL queries in it. The first query we will write is the CONTINENT_QUERY:

import { gql } from "@apollo/client";

export const CONTINENT_QUERY = gql`
  query ContinentQuery {
    continents {
      code
      name
    }
  }
`;

This will fetch a list of continent names and code from the countries API.

Back in HomeScreen.js, we import the CONTINENT_QUERY and a hook called useQuery to execute this query via Apollo Client.

import { useQuery } from "@apollo/client";
import { CONTINENT_QUERY } from "./gql/Query";

And we add the logic to fetch the data in HomeScreen:

  1. Execute the query using useQuery
  2. While loading is true, return a Text that has 'Fetchind data...'
  3. Return a FlatList component that displays all the continent names
export default function HomeScreen() {
  const { data, loading } = useQuery(CONTINENT_QUERY); //execute query

  const ContinentItem = ({ continent }) => {
    const { name, code } = continent; //get the name of continent

    return (
      <Pressable>
        <Text>{name}</Text> //display name of continent
      </Pressable>
    );
  };

  if (loading) {
    return <Text>Fetching data...</Text> //while loading return this
  }

  return (
      <FlatList
        data={data.continents}
        renderItem={({ item }) => <ContinentItem continent={item} />}
        keyExtractor={(item, index) => index}
      />
  );
}

And now, we can test our app by running:

expo start

We should have a list of continents being fetched and displayed!

image.png

Thanks for reading! I hope this has been helpful to get you started working with GraphQL APIs on React Native apps.

Before we wrap up this tutorial, if you would like a challenge, how about try to add more queries such as fetching names of the countries under each continent?

Here's my example! Code will be in this repo for your reference.

test.gif

Ultimately, practising and building projects will help you to be more familiar with Apollo Client, GraphQL and React Native. Please do not hesitate to leave questions, share this article and refer to the References section below for more reading. Cheers!


Comments

Popular Posts

Reloading UITableView while Animating Scroll in iOS 11

Reloading UITableView while Animating Scroll Calling  reloadData  on  UITableView  may not be the most efficient way to update your cells, but sometimes it’s easier to ensure the data you are storing is in sync with what your  UITableView  is showing. In iOS 10  reloadData  could be called at any time and it would not affect the scrolling UI of  UITableView . However, in iOS 11 calling  reloadData  while your  UITableView  is animating scrolling causes the  UITableView  to stop its scroll animation and not complete. We noticed this is only true for scroll animations triggered via one of the  UITableView  methods (such as  scrollToRow(at:at:animated:) ) and not for scroll animations caused by user interaction. This can be an issue when server responses trigger a  reloadData  call since they can happen at any moment, possibly when scroll animation is occurring. Example of s...

What are the Alternatives of device UDID in iOS? - iOS7 / iOS 6 / iOS 5 – Get Device Unique Identifier UDID

Get Device Unique Identifier UDID Following code will help you to get the unique-device-identifier known as UDID. No matter what iOS user is using, you can get the UDID of the current iOS device by following code. - ( NSString *)UDID { NSString *uuidString = nil ; // get os version NSUInteger currentOSVersion = [[[[[UIDevice currentDevice ] systemVersion ] componentsSeparatedByString: @" . " ] objectAtIndex: 0 ] integerValue ]; if (currentOSVersion <= 5 ) { if ([[ NSUserDefaults standardUserDefaults ] valueForKey: @" udid " ]) { uuidString = [[ NSUserDefaults standardDefaults ] valueForKey: @" udid " ]; } else { CFUUIDRef uuidRef = CFUUIDCreate ( kCFAllocatorDefault ); uuidString = ( NSString *) CFBridgingRelease ( CFUUIDCreateString ( NULL ,uuidRef)); CFRelease (uuidRef); [[ NSUserDefaults standardUserDefaults ] setObject: uuidString ForKey: @" udid " ]; [[ NSUserDefaults standardUserDefaults ] synchro...

Xcode & Instruments: Measuring Launch time, CPU Usage, Memory Leaks, Energy Impact and Frame Rate

When you’re developing applications for modern mobile devices, it’s vital that you consider the performance footprint that it has on older devices and in less than ideal network conditions. Fortunately Apple provides several powerful tools that enable Engineers to measure, investigate and understand the different performance characteristics of an application running on an iOS device. Recently I spent some time with these tools working to better understand the performance characteristics of an eCommerce application and finding ways that we can optimise the experience for our users. We realised that applications that are increasingly performance intensive, consume excessive amounts of memory, drain battery life and feel uncomfortably slow are less likely to retain users. With the release of iOS 12.0 it’s easier than ever for users to find applications that are consuming the most of their device’s finite amount of resources. Users can now make informed decisions abou...