Beginner’s Guide to GraphQL in React Native & React(1/3)(Updated)

Ali Alhaddad
8 min readSep 25, 2018

We will explain GraphQL, and build a basic GraphQL server for this part of the guide.

“turned on iMac and displaying game application” by Aral Tasher on Unsplash

So what is GraphQL?

GraphQL is a query language, where you would define schemas or the structure of your data such as object types, resolvers which will execute each field in the schema, and connectors which are for defining or retrieving your database instance for your resolvers, which will return the data indicated by the schema. It enables a versionless server, which means that the API will update itself. It also enables pagination and other cool features.

GraphQL vs REST?

GraphQL server can be accessed from one endpoint, which will send our entire server.

In REST server it will implement a part of the server via per each endpoint, resulting with multiple endpoints. Due to the fact in order to get parts of the data, you would need multiple endpoints.

While in GraphQL you can the alter your schema in your frontend to retrieve the data you would like instead of over fetching or under fetching data.

REST can do everything literally. While in the case of GraphQL it can only do so much. Especially when dealing with images.

REST is being accessed via endpoints, in a linear fashion, while GraphQL is accessed via the schema based on relationships.

This a quick overview of REST and GraphQL and differences between the two.

Now are gonna build an app which will be in React Native, and React, that will implement a list of top 25 NFL players. How we will create it, will be different in React compared to React Native.

But before anything build a mongodb database in mlab. Here is a tutorial for it.

Then add each of these objects as a document.

We will first create a project in React Native, then create a node project with our server and a seperate package.json file for it, and do a react-native init in our project folder and call it top25NFLPlayers.

If you don’t have your environment setup for React Native follow this guide from facebook. If you don’t want to do React Native then skip this part of the tutorial or set it up using this link.

mkdir top25NFLPlayerMobile 
cd top25NFLPlayerMobile
npm init -y
react-native init top25NFLPlayers

Now let’s start setting up our server. We will create a server folder which hold our index.js

mkdir server && cd server
touch index.js

Then regardless of what folder, as long it isn’t in our React Native project, and not outside our top25NFLPlayersMobile directory install needed dependencies and devDependencies.

We will first start our devDependencies that will responsible for starting up our server.

npm i -D nodemon babel-cli babel-preset-es2015 babel-preset-stage-2

Then we will install our dependencies.

npm i -S apollo-server graphql graphql-tools mongoose dotenv

Here is a breakdown of our dependencies.

apollo-server — Responsible for starting server using graphql. Primarily used for defining shape of dat and fetching it.

graphql — Enables the graphql schema language.

graphql-tools — Enables the use of (`) for defining your schemas. Can just use backticks or the gql tags from apollo-server.

dotenv — Enable a env file, which holds your connection string.

Now setup your package.json with by adding a start property in your scripts property and remove test property, to indicate how your server is ran.

nodemon(not required) — watch server( Watches server.)

— watch package.json server/index(watches package.json and runs server.)

— exec babel-node(use babel on node.)

— presets es2015,stage-2(watches specific version of ecmescript)

Now we will start building our server, and configure it by creating basic type definitions and resolvers to just to get our server working.

Start a simple server

We import our named exports from apollo-server which will be ApolloServer, and gql.

ApolloServer← your server that will take typeDefs and resolvers at the moment.

gql←for defining your schema’s.

We will define our type definitions or our Query type which will be assigned to our query keyword in our schema. Then we will define our resolvers which will indicate how each field of our Query type is executed. Now run npm start.

npm start

Now go to localhost:4000 and run your GraphQL schema getting your helloString property.

Graphql playground.

Congratulations our GraphQL server is running!!

Now we will create our server for retrieving data from our database.

First create .env file outside of the server directory.

Then define your connection string with your database connection string.

CONNECTION_STRING = <CONNECTION STRING>

Then create a .gitignore so you can ignore your node_modules and .env when your repo is committed to git if you decide to do that.

/node_modules
.env

Now let’s create a typeDefs.js file which will hold your type definitions for your schema.

Then create a resolvers.js file which will indicate how the schema’s fields are executed.

Then a connectors.js file which will connect to your database and then define your Player model to retrieve data from the database.

All these files will be within your server directory.

touch typeDefs.js resolvers.js connectors.js

Now let connect to our database in our connectors.js file.

connect to your database.

We will import mongoose then assign our Mongoose Schema instance to our Schema variable which will define our models.

Then we will use the connect method using three arguments.

Our connection string.

Our options with our useNewUrlParser set to true.

Our callback with a error argument if there is an error console.log it.

Now we will define our mongoose models that will retrieve the players from our database.

Define your Player Model

We will define our Player model.

It will have a position, name, team, jerseyNumber, and wonSuperBowl which is a boolean.

Now we will define our type definitions which will have our Query type with a players field which will return an array of Player object types. Then we will define our Player object type with position, name, team, jerseyNumber, and wonSuperBowl field. Make sure when defining your schema understand that the schema will only retrieve the data specified.

Define your type definitions for your schema.

Now define how your fields are executed, which will be a callback assigned to each field for your Query object type, since assigned to the query keyword.

Define how your fields are executed.

In our callback we are implicitly returning all the data from the players collection, using the Player.find method. Then we will export the resolvers.

Go to your index.js file, and import your type definitions and resolvers from the typeDefs and resolvers js file. Then pass those as your arguments for your ApolloServer instance.

Your index.js file should look like this.

Your Apollo Server

Now if you run your graphql playground you should get all the players.

Graphql Server

That is for the React Native server. We will work on the React server next.

Now we will create a react app. We will install the needed dependencies, except the devDependencies since we can have a proxy and main property in our package.json to connect to our server and run it.

Then we will install our dependencies.

npm i -S apollo-server graphql graphql-tools mongoose dotenv

Here is a breakdown of our dependencies.

apollo-server — Responsible for starting server using graphql. Primarily used for defining shape of dat and fetching it.

graphql — Enables the graphql schema language.

graphql-tools — Enables the use of (`) for defining your schemas. Can just use backticks or the gql tags from apollo-server.

dotenv — Enable a env file, which holds your connection string.

Afterwards go to your package.json give it two properties main, and a proxy.

main ← Will be set to our main server file.

proxy ← Will be set to our apollo server.

Add main and proxy properties to your package.json

Now we will create a server directory within our root. In this directory we will create a index.js file which will hold our graphql server.

mkdir server
cd server
touch index.js

We will just make sure our server is running.

We will first configure our env file by importing dotenv and using the config method on the top of the index file.

Afterwards we will import ApolloServer for defining our server, and gql for defining our schema from apollo-server.

Then define our Port which will be 5000.

We will create a basic type definition for our Query type which will be set to our query keyword for our schema.

We will create a resolvers nested object which will indicate how the schema is executed.

We will then create our apollo-server instance with those arguments(typeDefs, resolvers).

Have your basic react/graphql server running.

Now run your server, and then go to http://localhost:5000. It should be where your GraphQL playground is setup at.

Now you just started your first React/GraphQL server.

Now define your CONNECTION_STRING environment variable that connects to mongodb connection string.

CONNECTION_STRING=<MongoDB Connection String>

And add your .env file in your .gitignore if you are gonna submitted to github since info is protected.

We will now create a typeDefs.js, resolvers.js, and a connectors.js file. Within your server directory.

touch typeDefs.js resolvers.js connectors.js

The typeDefs.js file will hold all your type definitions.

The resolvers.js file will contain your resolvers nested object.

The connectors.js file will contain your app connecting to the database.

First we will connect to our database. We will import mongoose for connecting to our database, and assign a Schema variable to mongoose.Schema instance.

Connect to your mongodb database using mongoose.

Now we will create a mongoose model with properties of position, name, team, jerseyNumber, and wonSuperbowl. Then we will export our model.

Define your Player Model

Now let’s define our type definitions which will have one field in our Query object type which will be players that will return an array of Player object types.

Define your type definitions for your server.

The Player object type will contain position, name, team which will return a String scalar type. Then jerseyNumber and wonSuperbowl which will return Int and Boolean scalar types.

Now we will create a resolvers nested object, which will indicate how our fields are executed. We will first import our Player model which will be responsible for retrieving data from our players collection.

Define how your fields in your schema are executed.

In our Query object which will have a players properties which will be set to a callback returning the Player.find method, and return the data.

Now we will import our typeDefs and resolvers, and pass those 2 arguments to our new ApolloServer instance.

Define your server.

Now run your server, and you should now see your data.

Data Retrieved!

Now we just completed our React and React Native GraphQL server.

Here is my GitHub repo for React Native for reference.

Here is my GitHub repo for React for reference.

Here is the second part.

Follow me on medium, instagram and linkedin.

Instagram:

https://www.instagram.com/alooshie_97/

Linkedin:

https://www.linkedin.com/in/ali-alhaddad/

Happy Coding!

--

--