Building Chatty — Part 1: Setup

A WhatsApp clone with React Native and Apollo

This is the first blog in a multipart series where we will be building Chatty, a WhatsApp clone, using React Native and Apollo. You can view the code for this part of the series here.

Overview

Each part of this series will be focused on teaching a core concept of Apollo or React Native. We’ll start from scratch, and by the end of the series, we’ll have a kick-ass group messaging application with real-time updates.

7 Steps later…

Steps

  1. Setup
  2. GraphQL Queries with Express
  3. GraphQL Queries with React Apollo
  4. GraphQL Mutations & Optimistic UI
  5. GraphQL Pagination
  6. GraphQL Subscriptions
  7. GraphQL Authentication

Future posts beyond the core series will cover more complex features like push notifications, file uploads, and query optimizations.

Since we are using shiny new tech, this series will be a living document. I will update each post as the tools we use continue to advance. My goal is to use this series as a best practices model for building a complex application using some of the best software available.

With that in mind, if you have any suggestions for making this series better, please leave your feedback!

The Stack

Chatty will use the following stack:

  • Server: Express
  • Client: React Native
  • Middleware: Apollo (GraphQL)
  • Database: SQL (sqlite to start)

This is a pretty awesome stack for building complex real-time native applications.

For those of you who are new to Apollo, I just want to point out some of the coolest built-in features for Apollo with React:

  • Smart query caching (client side state gets updated and cached with each query/mutation)
  • Subscriptions (realtime updates pushed by server)
  • Optimistic UI (UI that predicts how the server will respond to a request)
  • SSR support
  • Prefetching

That’s a ton of buzzwords! In the end, what that all really adds up to is our app will be data driven, really fast for users, and get real-time updates as they happen.

Part 1 Goals

Here’s what we are going to accomplish in this first tutorial:

  1. Set up our dev environment
  2. Start a basic express server
  3. Create our first GraphQL Schema
  4. Start a basic React Native client
  5. Connect our express server and RN client with Apollo

Getting started

For this tutorial series, we’re going to start from absolute scratch. My style is to keep everything really simple and refactor as we add complexity. Let’s start with this basic directory structure:

/chatty
/node_modules
package.json
/server
... express files
/client
/node_modules
package.json
... RN files

We will keep our React Native code separate from our server code. This will also keep server dependencies separate from React Native dependencies, which means we will have 2 package.json files. That may sound weird/bad, but trying to get everything set up with one packager is a huge hassle. It will also save us from a few other issues down the line.

Here’s the terminal code to get us started:

Step 1.1: Create package.json and index.js

# make our directory
mkdir chatty
cd chatty
# start yarn package managing
yarn init
# build some server folders and files
mkdir server
cd server
touch index.js

Setting up the dev environment

We’ll start setting up our dev env with the following features:

  1. Server stays running and reloads when we modify code
  2. ES6 syntax including import syntax in our server code
  3. ESLint with AirBNB presets
# from root dir..
# add dev dependencies
yarn global add eslint-cli # eslint is an excellent linter
yarn add --dev babel-cli babel-preset-es2015 babel-preset-stage-2 nodemon eslint babel-eslint
eslint --init # choose airbnb preset or your preferred setup

My eslintrc.js file looks like this:

Step 1.2: Add eslint, babel, and nodemon

Added .eslintrc.js

...
module.exports = {
"parser": "babel-eslint",
"extends": "airbnb",
"plugins": [
"react",
"jsx-a11y",
"import"
],
"rules": {
"react/jsx-filename-extension": [1, { "extensions": [".js", ".jsx"] }],
"react/require-default-props": [0],
"react/no-unused-prop-types": [2, {
"skipShapeProps": true
}],
"react/no-multi-comp": [0],
"no-bitwise": [0],
},
};

Create our start script inside package.json:

Step 1.3: Create start script

Changed package.json

...
  "repository": "https://github.com/srtucker22/chatty.git",
"author": "Simon Tucker <srtucker22@gmail.com>",
"license": "MIT",
"scripts": {
"start": "nodemon --watch server --watch package.json server/index.js --exec babel-node --presets es2015,stage-2"
},
"devDependencies": {
"babel-cli": "^6.24.1",
"babel-eslint": "^8.2.1",

Starting the Express server

Let’s import express in index.js using ES6 syntax.

  1. yarn add express
  2. Add the following to index.js:

Step 1.4: Add express

Changed server/index.js

...
import express from 'express';
const PORT = 8080;
const app = express();
app.listen(PORT, () => console.log(`Server is now running on http://localhost:${PORT}`));

Quickly verify our setup works by running yarn start.

We have a great starting point. Our start script will transpile ES6 code, spin up our express server, and refresh as we make changes to server code. Nice!

Adding GraphQL to Express

GraphQL in a nutshell is a query language for APIs. It’s a middleware that sits between your server side data and your client. It allows your client to query for exactly what it needs in one single trip and nothing more. You can check out GraphQL’s homepage for some sweet visualizations illustrating why GraphQL is so cool.

We’ll start by creating a basic GraphQL Schema. A Schema establishes the data types the client can request and how the client is allowed to request them.

We’ll create a new folder /server/data and add a new file schema.js:

Step 1.5: Create basic schema

Added server/data/schema.js

...
export const Schema = [
`type Query {
testString: String
}
schema {
query: Query
}`,
];
export default Schema;

Apollo requires a list of strings written in GraphQL’s language to establish a Schema. This Schema will just be a basic placeholder for now. We will add more advanced and meaningful Schemas in the next tutorial.

We also need our Schema to work with data. A great way to get Schemas up and running is by mocking data. Mocking data also happens to be useful for testing, so it’s good practice to start using mocks with Schemas before attaching real data like a database or 3rd party API.

We’ll add the file /server/data/mocks.js:

Step 1.6: Create basic mocks

Added server/data/mocks.js

...
export const Mocks = {
String: () => 'It works!',
};
export default Mocks;

Using the Mocks Object, we will be able to convert all Strings returned by GraphQL queries to “It works!”

We want to add a GraphQL endpoint to our server in server/index.js so clients can use GraphQL with our server. First we need to add the following dependencies:

yarn add body-parser graphql apollo-server-express graphql-tools

We’ll rewrite server/index.js as follows (explanation below):

Step 1.7: Add graphqlExpress

Changed server/index.js

...
import express from 'express';
import { graphqlExpress, graphiqlExpress } from 'apollo-server-express';
import { makeExecutableSchema, addMockFunctionsToSchema } from 'graphql-tools';
import bodyParser from 'body-parser';
import { createServer } from 'http';
import { Schema } from './data/schema';
import { Mocks } from './data/mocks';
const GRAPHQL_PORT = 8080;
const app = express();
const executableSchema = makeExecutableSchema({
typeDefs: Schema,
});
addMockFunctionsToSchema({
schema: executableSchema,
mocks: Mocks,
preserveResolvers: true,
});
// `context` must be an object and can't be undefined when using connectors
app.use('/graphql', bodyParser.json(), graphqlExpress({
schema: executableSchema,
context: {}, // at least(!) an empty object
}));
app.use('/graphiql', graphiqlExpress({
endpointURL: '/graphql',
}));
const graphQLServer = createServer(app);
graphQLServer.listen(GRAPHQL_PORT, () => console.log(`GraphQL Server is now running on http://localhost:${GRAPHQL_PORT}/graphql`));

What we’ve done is add Apollo’s graphqlExpress and graphiqlExpress middleware for the /graphqlendpoint. The graphqlExpress middleware enables clients to retrieve data by querying with our Schema. However, since we don’t have real data yet, we can use Mocks to fake the data when our schema is queried by using addMockFunctionsToSchema.

We’ve also added a second endpoint /graphiql, which uses the graphiqlExpress middleware. This middleware connects to our GraphQL endpoint and displays an UI for sending GraphQL queries to our server, called GraphIQL.

Let’s test it all out. Open http://localhost:8080/graphiql and you should see the GraphIQL interface. Type in {testString} and you should get back the proper response:

GraphIQL is cool!

Great! So now we have a server that runs the most basic GraphQL. We could build up our GraphQL backend a bit more, but I’d prefer to connect our server and React Native client before we make our Schema any more complex.

Starting the React Native client

First we’ll download the dependencies and initialize our React Native app. For the sake of brevity, I’m going to focus on iOS, but all our code should also work with Android.

# from root dir...
yarn global add react-native-cli
# initialize RN with name chatty
react-native init chatty
# change name of RN folder to client
mv chatty client
# run the app in simulator
cd client
react-native run-ios # and grab a snack or something cause this might take a while the first run...

Running the initialization will create an index.ios.js file. In this file is boilerplate code that creates a React component and registers it with AppRegistry, which renders the component.

Let’s pull out the Chatty component from index.ios.js and stick it in its own file. I prefer to organize my files by type rather than feature, but you’re welcome to organize differently if you feel strongly about it.

So I’m going to place the Chatty component code into client/src/app.js and rename the component App.

Step 1.9: Move app code to /src

Changed client/index.js

...
import { AppRegistry } from 'react-native';
import App from './src/app';
AppRegistry.registerComponent('chatty', () => App);

Changed client/App.js

...
  Platform,
StyleSheet,
Text,
View,
} from 'react-native';
const instructions = Platform.select({
...
    'Shake or press menu button for dev menu',
});
export default class App extends Component {
render() {
return (
<View style={styles.container}>

Adding Apollo to React Native

We’re going to modify app.js to use React-Apollo and Redux. While Apollo can be used sans Redux, the developer experience for React Native is much sweeter with Redux for monitoring our app's state, as you'll soon see.

We need to add a bunch of Apollo packages and a couple Redux ones:

# make sure we're adding all react native and client related packages to package.json in the client folder!!!
cd client
yarn add apollo-cache-redux apollo-client apollo-link apollo-link-error apollo-link-http apollo-link-redux graphql graphql-tag react-apollo react-redux redux redux-devtools-extension

We need to do the following:

  1. Create a Redux store
  2. Create an Apollo client
  3. Connect our Apollo client to our GraphQL endpoint via apollo-link-http
  4. Catch and log any GraphQL errors via apollo-link-error
  5. Connect Redux to our Apollo workflow via apollo-link-redux. This will let us track Apollo events as Redux actions!
  6. Set our Apollo client’s data store (cache) to Redux via apollo-cache-redux

We can also swap out compose for composeWithDevTools, which will let us observe our Redux state remotely via React Native Debugger.

Step 1.10: Add ApolloClient

Changed client/package.json

...
{
"name": "chatty",
"version": "0.0.1",
"private": true,
"scripts": {
"start": "node node_modules/react-native/local-cli/cli.js start",
"test": "jest"
},
"dependencies": {
"apollo-cache-redux": "^0.1.0-alpha.7",
"apollo-client": "^2.2.5",
"apollo-link": "^1.1.0",
"apollo-link-error": "^1.0.7",
"apollo-link-http": "^1.3.3",
"apollo-link-redux": "^0.2.1",
"graphql": "^0.12.3",
"graphql-tag": "^2.4.2",
"react": "^16.3.0-alpha.1",
"react-apollo": "^2.0.4",
"react-native": "0.54.2",
"react-redux": "^5.0.5",
"redux": "^3.7.2",
"redux-devtools-extension": "^2.13.2"
},
"devDependencies": {
"babel-jest": "22.4.1",
"babel-preset-react-native": "4.0.0",
"jest": "22.4.2",
"react-test-renderer": "16.2.0"
},
"jest": {
"preset": "react-native"
}
}

Changed client/src/app.js

...
import React, { Component } from 'react';
import {
Platform,
...
  View,
} from 'react-native';
import { ApolloClient } from 'apollo-client';
import { ApolloLink } from 'apollo-link';
import { ApolloProvider } from 'react-apollo';
import { composeWithDevTools } from 'redux-devtools-extension';
import { createHttpLink } from 'apollo-link-http';
import { createStore, combineReducers } from 'redux';
import { Provider } from 'react-redux';
import { ReduxCache, apolloReducer } from 'apollo-cache-redux';
import ReduxLink from 'apollo-link-redux';
import { onError } from 'apollo-link-error';
const URL = 'localhost:8080'; // set your comp's url here
const store = createStore(
combineReducers({
apollo: apolloReducer,
}),
{}, // initial state
composeWithDevTools(),
);
const cache = new ReduxCache({ store });
const reduxLink = new ReduxLink(store);
const errorLink = onError((errors) => {
console.log(errors);
});
const httpLink = createHttpLink({ uri: `http://${URL}/graphql` });
const link = ApolloLink.from([
reduxLink,
errorLink,
httpLink,
]);
export const client = new ApolloClient({
link,
cache,
});
const instructions = Platform.select({
ios: 'Press Cmd+R to reload,\n' +
'Cmd+D or shake for dev menu',

Finally, we wrap our App component in the ApolloProvider component from react-apollo. ApolloProvider connects our app to Redux and Apollo at the same time.

Step 1.11: Add ApolloProvider to App

Changed client/src/app.js

...
export default class App extends Component {
render() {
return (
<ApolloProvider client={client}>
<Provider store={store}>
<View style={styles.container}>
<Text style={styles.welcome}>
Welcome to React Native!
</Text>
<Text style={styles.instructions}>
To get started, edit App.js
</Text>
<Text style={styles.instructions}>
{instructions}
</Text>
</View>
</Provider>
</ApolloProvider>
);
}
}

If we reload the app (CMD + R), there hopefully should be no errors in the simulator. We can check if everything is hooked up properly by opening Redux Native Debugger and confirming the Redux store includes apollo:

That’s one small step for man…

Hello world!

You have successfully created a solid setup for a full-stack Apollo app with Express and React Native. In the next step, we are going to expand our GraphQL Schema, add Queries, and connect real data from a database.

As always, please share your thoughts, questions, struggles, and breakthroughs below!

You can view the code for this tutorial here

Continue to Building Chatty — Part 2 (GraphQL Queries with Express)