In the previous post I added a React Native ticking timer. I now have enough client-side parts and it’s time to wire up the client app to a server. This cookbook should be helpful to anyone doing it for the first time.
Rails Server
Boilerplate
Make a Rails API server with MongoDB.
- Create a server with
rails new server --skip-active-record -T --api
, 33-minutes-server@74fd5a. - Generate a MongoDB config with
rails g mongoid:config
, 33-minutes-server@3e1c6f. - Add RuboCop, my workflow typically consists of
rubocop -a ; rubocop --auto-gen-config
, 33-minutes-server@fc034c. - Add RSpec, 33-minutes-server@3af9b9.
- Enable Travis-CI, 33-minutes-server@8050ab.
GraphQL Controller
Follow my tutorial on exposing a GraphQL API and use warden to keep authenticated user context. Since Warden requires cookies, re-add the ActionDispatch::Cookies
middleware to config/application.rb
.
A GraphQL mutation creates a user.
Similar GraphQL mutations login and logout users.
When serializing users with Warden, don’t serialize the whole object or you’ll get a ActionDispatch::Cookies::CookieOverflow
exception.
You can see the entire code in 33-minutes-server@52a249 and 33-minutes-server@0c3c4d.
Schema IDL
Run rake graphql:schema:idl
to generate a schema.graphql
file and copy it to the client app’s schema
folder. This will have to be done every time the Rails API GraphQL schema changes.
React Native Client
Signed In vs. Signed Out
I used a switch navigator to toggle between the signed-in and signed-out states in 33-minutes-app@9f252c. Each state is its own stack navigator.
The entire app is that navigator.
To toggle between the states, navigate to either SignedIn
or SignedOut
(see the mutations below).
Relay Boilerplate
The Relay Quick Start Guide is pretty good. We throw in react-relay
with yarn add react-relay
and relay-compiler
with yarn add -dev relay-compiler
. Add a relay
script into package.json
.
Run yarn relay
. Generally you will be running yarn relay --watch
, which generates JavaScript code under a __generated__
folders every time something changes. You will also have to restart this process when schema changes. This is not integrated with the rest of the compiler toolchain because that would be too easy.
Environment
Copy-paste a relay environment into app/Environment.js
. Note my hard-coded https://localhost:3000/graphql
for the Rails server. I will make this dynamic in the future.
Create User Mutation
Copy-paste a relay-style mutation into app/mutations/CreateUserMutation.js
.
Create a User
Invoke the mutation, switch to a signed-in navigator upon success, or set an error message otherwise.
Login is very similar. For now we’re using cookies to store a session and don’t remember anything on the client, which means that reloading the app logs the user out.
Show Some Data
To show data wrap up a GraphQL query into a QueryRenderer. You’ll always need one.
Code
See 33-minutes-app@e3e6b9 for complete code. In the next post I’ll enable Relay-style pagination.