Beginners guide to Mutations with React Native and Relay

In this article, I show you how to add mutations (updates) to your React Native Relay application. If you have not already, follow the tutorial on getting started with React Native and Relay so that you already have a foundation.

Add the mutation to GraphQL

Open up app/models/schema.rb in your Rails application. [1]

Begin by updating your Schema class to:

Schema =
  query: QueryRoot,
  mutation: MutationRoot

Next at the top off that same app/models/schema.rb file, add the following:

CreateUserMutation = GraphQL::Relay::Mutation.define do
  name 'CreateUser'

  input_field :email, !types.String

  return_field :user, UserType

  resolve -> (inputs, ctx) {
    user = User.create(email: inputs[:email])
    { user: user }

MutationRoot = GraphQL::ObjectType.define do
  name 'Mutation'
  description 'Mutations of our application'

  field :createUser, field: CreateUserMutation.field

Great work! You just added your first GraphQL mutation.

Start that server up.

bin/rails s -b -p 3000

Add the mutation to React Native Relay

Now that GraphQL is serving up the mutation createUser, we can make use of it in our React Native Relay application. [2]

In index.ios.js., add the following code inside class RelayApp.

class RelayApp extends Component {
  componentWillMount () {
    const mutation = new CreateUserMutation()

Next we need to build the actual mutation. Place the following code right above the class RelayApp.

class CreateUserMutation extends Relay.Mutation {
  getMutation () {
    return Relay.QL`mutation{ createUser }`

  getVariables () {
    return {
      email: ''

  getFatQuery () {
    return Relay.QL`
      fragment on User {

  getConfigs () {
    return [{
      type: 'FIELDS_CHANGE',
      fieldIDs: {}

That's it. You just created your first mutation in Relay.

You might be saying to yourself, "what does all this do" and "sure does seem like a lot of ceremony for just a little update", and I would agree with you. But I'm not going to go into all the details in this post. For now, I will say that mutations are a weak point of Relay at this time. The API is verbose, but the Relay team is working on simplifying the API.

Boot up your React Native RelayApp to see it in action.

react-native run-ios

That's it! As soon as the component mounts it will have created a new User.

You'll want to move the createUser mutation to a better location. For example, you probably want it to be called at the moment a user clicks a Signup button. I'll leave that as an exercise for the reader or as a later post.

[1] /2016-05-07-getting-started-with-rails-graphql.html
[2] /2016-05-08-getting-started-with-react-native-and-relay.html