Getting started with GraphQL in React Native
You will need to have Node 11.2+, Yarn 1.13+, React Native CLI 2.0+ and React Native 0.59+ installed on your machine.
GraphQL’s adoption is increasing, and for good reason. Many believe it’s the future for API’s, and big companies (GitHub, Coursera, PayPal, Shopify) using it just sparks the developer interest even further.
It’s really an exciting time to learn GraphQL, especially for React Native developers because the apps that we create usually communicate with a server. GraphQL makes it easier for us to get the specific data we want with less code. Gone are the days where we have to hit multiple endpoints just to get the data we want from a REST API.
In this tutorial, you will learn how to implement a simple GraphQL server and query the data from a React Native app.
Prerequisites
Basic knowledge of React Native and Node.js is required to follow this tutorial.
The following package versions are used in this tutorial:
- Node 11.2.0
- Yarn 1.13.0
- React Native CLI 2.0.1
- React Native 0.59.5
If you encounter any issues getting the app to work, try using the above versions instead.
App overview
We will build a Pokemon viewer app. This will pick a random Pokemon and display it on the screen. When the user taps on it, a new Pokemon will be fetched. It’s really simple but it’s still going to demonstrate how to implement the full GraphQL stack.
You can view the source code of the app on this GitHub repo.
Bootstrapping the app
To ensure compatibility, clone the GitHub repo for this project:
git clone https://github.com/anchetaWern/RNGraphQL
This contains the package.json
file for both the server and the React Native app. The starter
branch contains the starting point for this tutorial:
git checkout starter
Once you’ve switched branches, you can go ahead and install the dependencies and re-create the android
and ios
folders for the app:
yarn
react-native eject
That will install all the GraphQL-related packages that we’re going to need in the app. Later on, you’ll learn what each one does once we proceed to code the client side.
Lastly, we also need to install the server dependencies:
cd server
yarn
Creating the GraphQL server
In this section, we will be creating the GraphQL server using Apollo. As you might already know, GraphQL is only a specification, not an implementation. That’s why we need something like Apollo to implement it.
Apollo is a platform which provides us with all the tools needed for implementing a GraphQL server. This includes both the server and the client. The server component is used for defining the schema and resolvers (provides instructions on how to turn a specific GraphQL operation into data). On the other hand, the client component is responsible for providing tools that we can use for querying the server and binding the results to the UI.
Defining the schema
The first step in creating a GraphQL server is for us to define the schema. This is where you strictly define what data your API is managing. In this case, we’re handling basic Pokemon data.
If you’ve seen the demo gif earlier, you know exactly which Pokemon data we’re working with:
- Name
- Image
- Types
- Description
But aside from that, we also need to define the queries that the server is going to handle. In this case, we’re using the PokéAPI as our direct data source so our queries will be limited by the endpoints they’re exposing. We’re only going to need a few data from these endpoints so it’s fine if we use them directly:
/pokemon/{id}
- used for getting the Pokemon data./pokemon-species/{id}
- used for getting the description text.
With that in mind, we know that we can only have queries which accept the ID of the Pokemon as its argument.
Note: We’re not really going to cover caching in this tutorial, but it’s important to implement it if you’re going to use an existing REST API as a direct data source. That way, you won’t get throttled from using the API too much. PokéAPI is actually limited to 100 API requests per IP address per minute.
Now we’re ready to define the schema. Create a server/schema.js
file and add the following code:
const { gql } = require('apollo-server');
const typeDefs = gql`
type Query {
pokemon(id: ID!): Pokemon
}
type Pokemon {
id: ID!
name: String
desc: String
pic: String
types: [PokemonType!]!
}
type PokemonType {
id: Int!
name: String!
}
`;
module.exports = typeDefs;
Breaking down the above code, we first imported the apollo-server
package. This allows us to define the GraphQL schema. The schema includes the shape of the data we expect to return, as well as the shape of the queries.
Let’s first start with the Query
type which describes what data we can fetch. In this case, we only want the user to fetch Pokemon data so the query is named pokemon
. To specify arguments, you need to put them inside the parentheses right after the name of the query. In this case, we want the users to supply the ID of the Pokemon. An exclamation is added after it to indicate that it is a required argument. After that, we specify the return data after the colon (Pokemon
). This is a custom GraphQL object type which we’ll define next:
type Query {
pokemon(id: ID!): Pokemon
}
Next, we need to define the Pokemon
object type. This is where we specify all the properties (and their data type) that are available for this particular type. Most of the properties that we need to expose are only scalar types (ID
and String
):
ID
is a unique identifier for a specific object of this type. An exclamation is added after it which means it cannot have a value ofnull
.String
is just your usual primitive type for storing string values.PokemonType
is yet another object type. Thetypes
property is used for storing an array of objects so we also have to break down the object to its expected properties:
type Pokemon {
id: ID!
name: String
desc: String
pic: String
types: [PokemonType]
}
Here’s the definition of the PokemonType
:
type PokemonType {
id: Int
name: String
}
You can find more types on this cheat sheet.
Connect to a data source
Now that we’ve defined our schema, the next step is to connect to a data source. Apollo comes with a data source API, which you could use to easily connect to an existing database or a REST API. As mentioned earlier, we will be using PokéAPI as our data source. This API provides Pokemon data from all of the Pokemon games so it’s perfect for our needs.
Create a server/datasources/poke.js
file and add the following:
const { RESTDataSource } = require('apollo-datasource-rest');
class PokeAPI extends RESTDataSource {
constructor() {
super();
this.baseURL = 'https://pokeapi.co/api/v2/';
}
pokemonReducer(pokemon, pokemonSpecies) {
return {
id: pokemon.id || 0,
name: pokemon.name,
desc: this.getDescription(pokemonSpecies.flavor_text_entries),
pic: pokemon.sprites.front_default, // image URL of the front facing Pokemon
types: this.getTypes(pokemon.types)
};
}
getDescription(entries) {
return entries.find(item => item.language.name === 'en').flavor_text;
}
getTypes(types) {
return types.map(({ slot, type }) => {
return {
"id": slot, // the type's index
"name": type.name // the type's name (e.g. electric, leaf)
}
});
}
async getPokemonById({ id }) {
const pokemonResponse = await this.get(`pokemon/${id}`);
const pokemonSpeciesResponse = await this.get(`pokemon-species/${id}`);
return this.pokemonReducer(pokemonResponse, pokemonSpeciesResponse);
}
}
module.exports = PokeAPI;
If you’ve consumed any sort of REST API before (and I assume you have), the code above should easily make sense to you. The apollo-datasource-rest
package really makes this simple. This package exposes the RESTDataSource
class which allows us to make a request to a REST API:
const pokemonResponse = await this.get(`pokemon/${id}`); // this.post for POST requests
const pokemonSpeciesResponse = await this.get(`pokemon-species/${id}`);
From there, all we had to do was to extract the data that we need. The only thing you need to remember is that the data you’re extracting should correspond to the properties that you’ve defined earlier in your schema: id
, name
, desc
, pic
, and types
:
pokemonReducer(pokemon, pokemonSpecies) {
return {
id: pokemon.id || 0,
name: pokemon.name,
desc: this.getDescription(pokemonSpecies.flavor_text_entries),
pic: pokemon.sprites.front_default, // image URL of the front facing Pokemon
types: this.getTypes(pokemon.types)
};
}
Define the resolvers
The final piece of the puzzle is the resolvers. The resolvers allow us to define the mapping of the queries you’ve defined in your schema to the data source method which returns the data. It follows the format:
fieldName: (parent, args, context, info) => data;
Here’s what each one does:
parent
- an object that contains the result returned from the resolver on the parent type. This is always blank (_
) because it refers to the root of the graph.args
- an object containing the arguments passed to the field. In this case, our query only accepts theid
of the Pokemon. We then need to pass theid
to the data source method (getPokemonById()
) as an object property because that’s how we defined it earlier on theserver/datasources/poke.js
file.context
- this is where we can access our data sources. We can extract the data source from thedataSources
property.info
- an object which contains information about the execution state of the operation. We don’t really need to use it in this case so we just won’t supply it at all.
To define the resolver, create a server/resolvers.js
file and add the following:
module.exports = {
Query: {
pokemon: (_, { id }, { dataSources }) =>
dataSources.pokeAPI.getPokemonById({ id })
}
};
Creating the server
The final step in implementing the GraphQL server is to bring everything together. Create a server/index.js
file and add the following:
const { ApolloServer } = require('apollo-server');
const typeDefs = require('./schema');
const resolvers = require('./resolvers');
const PokeAPI = require('./datasources/poke');
const server = new ApolloServer({
typeDefs,
resolvers,
dataSources: () => ({
pokeAPI: new PokeAPI()
})
});
server.listen().then(({ url }) => {
console.log(`GraphQL Server is running at ${url}`);
});
In the above code, we import the ApolloServer
class from the apollo-server
package. This allows us to fire up an Apollo server which accepts an object containing the schema, resolvers, and data sources we’ve defined earlier.
At this point, you can now run the server:
cd server
yarn start
You can play around with it by accessing http://localhost:4000/
on your browser.
If you get a blank screen, delete the node_modules
folder and yarn.lock
file. After that, remove the dependencies
property in the package.json
file and re-install the dependencies with the following command:
yarn add apollo-datasource-rest@0.4.0 apollo-server@2.5.0 graphql@14.3.0
From there, you can view the schema that we’ve defined earlier by clicking on the SCHEMA tab located on the right part of the screen:
But this interface is mostly used for testing out your queries. In this case, we want to fetch the Pokemon with the ID of 25:
query GetPokemonByName {
pokemon(id: 25) {
id,
name,
desc,
pic
}
}
That will return the following result:
{
"data": {
"pokemon": {
"id": "25",
"name": "pikachu",
"desc": "Its nature is to store up electricity. Forests\nwhere nests of Pikachu live are dangerous,\nsince the trees are so often struck by lightning.",
"pic": "https://raw.githubusercontent.com/PokeAPI/sprites/master/sprites/pokemon/25.png"
}
}
}
What if we also want to get the types of the Pokemon? Intuitively, we would just add types
to the properties we’ve specified:
query GetPokemonByName {
pokemon(id: 25) {
id,
name,
desc,
pic,
types
}
}
But that’s going to return an error:
The error says:
The field types of type [PokemonType] must have a selection of subfields.
This means that you also need to specify the subfields that you want to fetch like so:
query GetPokemonByName {
pokemon(id: 25) {
id,
name,
desc,
pic,
types {
id,
name
}
}
}
That will return the following:
{
"data": {
"pokemon": {
"id": "25",
"name": "pikachu",
"desc": "Its nature is to store up electricity. Forests\nwhere nests of Pikachu live are dangerous,\nsince the trees are so often struck by lightning.",
"pic": "https://raw.githubusercontent.com/PokeAPI/sprites/master/sprites/pokemon/25.png",
"types": [
{
"id": 1,
"name": "electric"
}
]
}
}
}
Building the app
Now that we’re done implementing the server, it’s time for us to add the code for the React Native app. Open the App.js
file and add the following:
import React, { Component } from "react";
import { View, Text, ActivityIndicator } from "react-native";
import { ApolloProvider, Query } from "react-apollo";
import ApolloClient from "apollo-boost";
import gql from "graphql-tag";
Here’s what each package does:
apollo-boost
- used for connecting to an Apollo server.react-apollo
- provides React components that allows us to fetch data from the Apollo server.graphql-tag
- used for parsing GraphQL queries into a format understood by the Apollo client.
Next, connect to the server that we created earlier. Replace the placeholder with your machine’s internal IP address. Be sure that your machine and your device are connected to the same network when you do so. You can also use ngrok if you want:
const client = new ApolloClient({ uri: 'http://YOUR_INTERNAL_IP_ADDRESS:4000/graphql' })
Next, import the component for rendering the Pokemon data as well as the helper function for generating random integers:
import Pokemon from "./src/components/Pokemon";
import getRandomInt from "./src/helpers/getRandomInt";
Next, we’re going to use the Context API so we can pass the Pokemon data through the component tree without having to pass props needed by the Pokemon
component down manually at every level:
export const AppContext = React.createContext({ data: { pokemon: null } });
Next, create the component and declare its default state. The query
contains the same query that we used earlier. We’re putting it in the state so the component will re-render every time we update it:
export default class App extends Component {
state = {
query: null
}
// next: add componentDidMount
}
Once the component is mounted, we generate the query and update the state:
componentDidMount() {
const query = this.getQuery();
this.setState({
query
});
}
Here’s the getQuery()
function. This generates a random ID and uses it for the query:
getQuery = () => {
const randomID = getRandomInt(1, 807);
return `
query GetPokemonById {
pokemon(id: ${randomID}) {
id,
name,
desc,
pic,
types {
id,
name
}
}
}
`
}
In the render()
method, the <ApolloProvider>
component is where we pass the client we created with the ApolloClient
earlier. Then we add the <Query>
component as its child, this is where you pass the query
. Don’t forget to parse the query
with the gql
module. By default, loading
will have a value of true
. In that case, we show a loading animation. Once the server responds, it can either be an error
or data
. The data
contains the same data you saw earlier when we tried running some queries. From there, we just pass the Pokemon data and the function for fetching a new one to the app’s context:
render() {
const { query } = this.state;
if (!query) return null;
return (
<ApolloProvider client={client}>
<Query query={gql`${query}`} >
{({ loading, error, data }) => {
if (loading || error) return <ActivityIndicator size="large" color="#0000ff" />
return (
<AppContext.Provider value={{...data.pokemon, onPress: this.onGetNewPokemon}} style={styles.container}>
<Pokemon />
</AppContext.Provider>
)
}}
</Query>
</ApolloProvider>
);
}
Here’s the onGetNewPokemon()
function:
onGetNewPokemon = () => {
const query = this.getQuery();
this.setState({
query
});
}
getRandomInt helper
Here’s the helper for generating random integers. Create the src/helpers
folder to house it:
// src/helpers/getRandomInt.js
const getRandomInt = (min, max) => {
min = Math.ceil(min);
max = Math.floor(max);
return Math.floor(Math.random() * (max - min + 1)) + min;
}
export default getRandomInt;
Pokemon component
The Pokemon
component is used for displaying the Pokemon data. Create a src/components
folder to house it.
Start by importing the packages we need:
// src/components/Pokemon.js
import React from 'react';
import { View, Text, Image, FlatList, TouchableOpacity } from 'react-native';
import { AppContext } from '../../App'; // import the context we exported earlier on the App.js file
Next, render the component. Wrap it in <AppContext.Consumer>
so you get access to the data and the onPress
function that we passed to the context earlier. From there, it’s just a matter of displaying the data using the right components:
const Pokemon = () => {
return (
<AppContext.Consumer>
{
({ name, pic, types, desc, onPress }) =>
<TouchableOpacity onPress={onPress}>
<View style={styles.mainDetails}>
<Image
source={{uri: pic}}
style={styles.image} resizeMode={"contain"} />
<Text style={styles.mainText}>{name}</Text>
<FlatList
columnWrapperStyle={styles.types}
data={types}
numColumns={2}
keyExtractor={(item) => item.id.toString()}
renderItem={({item}) => {
return (
<View style={[styles[item.name], styles.type]}>
<Text style={styles.typeText}>{item.name}</Text>
</View>
)
}}
/>
<View style={styles.description}>
<Text>{desc}</Text>
</View>
</View>
</TouchableOpacity>
}
</AppContext.Consumer>
);
}
Lastly, add the styles and export the component. Most of these are just used to change the background color of the types container based on the Pokemon’s type:
const styles = {
mainDetails: {
padding: 30,
alignItems: 'center'
},
image: {
width: 100,
height: 100
},
mainText: {
fontSize: 25,
fontWeight: 'bold',
textAlign: 'center'
},
description: {
marginTop: 20
},
types: {
flexDirection: 'row',
marginTop: 20
},
type: {
padding: 5,
width: 100,
alignItems: 'center'
},
typeText: {
color: '#fff',
},
normal: {
backgroundColor: '#8a8a59'
},
fire: {
backgroundColor: '#f08030'
},
water: {
backgroundColor: '#6890f0'
},
electric: {
backgroundColor: '#f8d030'
},
grass: {
backgroundColor: '#78c850'
},
ice: {
backgroundColor: '#98d8d8'
},
fighting: {
backgroundColor: '#c03028'
},
poison: {
backgroundColor: '#a040a0'
},
ground: {
backgroundColor: '#e0c068'
},
flying: {
backgroundColor: '#a890f0'
},
psychic: {
backgroundColor: '#f85888'
},
bug: {
backgroundColor: '#a8b820'
},
rock: {
backgroundColor: '#b8a038'
},
ghost: {
backgroundColor: '#705898'
},
dragon: {
backgroundColor: '#7038f8'
},
dark: {
backgroundColor: '#705848'
},
steel: {
backgroundColor: '#b8b8d0'
},
fairy: {
backgroundColor: '#e898e8'
}
}
export default Pokemon;
Running the app
At this point, you can now run the app:
react-native run-android
react-native run-ios
Conclusion
That’s it! In this tutorial, you learned the basics of using GraphQL in a React Native app. Specifically, you learned how to set up your own GraphQL server using Apollo, use an existing REST API as its data source, consume the data from a React Native app, and display it to the user.
Even though we’ve implemented the full stack on this tutorial, there’s still a lot more to learn. Be sure to check out the GraphQL and Apollo docs to learn more.
You can view the source code of the app on this GitHub repo.
24 June 2019
by Wern Ancheta