Getting started with React Native and GraphQL Step by Step

Today we are starting a new series of tutorial on “React Native and GraphQL”. We will start this series at a beginners level (so that it address to every one interested in the topic) and will take it to the most advance level possible.

What is GraphQL?

GraphQL is a query language and allows us to make queries just like SQL does.

Why I got  interested in this technology?

  1. GraphQL allows you to get result in single request for which you might have to make several request if you use REST API.
  2. GraphQL gives flexibility to  use ‘ready to use back-end’ or setup our own back-end server
  3. GraphQL is actively supported by open-source community

For ease of understanding, we will start playing with GraphQL using ‘ready to use backend’ . So, lets get started.

Step 1. Sign-up and create account with Graphcool here  and stay signed in till the end of this tutorial because CLI commands that we are going to use works only if you are sign-in to your account in browser.

Step 2. Install GraphQL CLI by using command below :

npm install -g graphcool

Step 3. Create a  React Native Project by using command below :

react-native init --version="0.42.0" ReactGraphQLApp

Step 4. If you are familiar with php and mysql, you must be knowing, when we start a project we first create a database. Similarly, here we will first create a graphql schema. So, get in the new react native project directory and fire command below :

graphcool init --name ReactGraphQLApp

The above command creates a new graphql project on graphcool server and also a project.graphcool file in the current directory. You will notice that two schema ‘File’ and ‘User’ are already there. Now, lets make some modification to the existing Schema.

Step 5. We will make simple modification by adding firstName and lastName to User schema. So, our new User schema looks like this :

type User implements Node {
  firstName: String
  lastName: String
  createdAt: DateTime!
  id: ID! @isUnique
  updatedAt: DateTime!
}

Notice, we haven’t added any exclamation mark to the new fields, because we don’t want to make it non-nullable. Adding exclamation mark makes field non-nullable.

Step 6. To update the changes we just made to local schema file, we need to fire command below :

graphcool push

( If you are a Laravel developer, you must be finding the above steps similar to the migration process used in Laravel to created db )

Step 7. Now we will install  react-apollo package. React-apollo package allows us to make graphql queries . (Remember GraphQL is just a query language, so, we need a package which allows us to use GraphQL queries in our React Native App. )  Install react-apollo package using the command below :

npm install react-apollo --save

Step 8. Now create a directory app inside your react native project root directory. In a  file App.js in the app directory. Now add the code below to the App.js file :

import React from 'react'
import { ApolloProvider, createNetworkInterface, ApolloClient } from 'react-apollo'
import Createuser from './components/Createuser'

const networkInterface = createNetworkInterface({ uri: 'https://api.graph.cool/simple/v1/cj8h0xusx000p01288nf9eemh' })
const client = new ApolloClient({ networkInterface })

export default (
  <ApolloProvider client={client}>
    <Createuser />
  </ApolloProvider>
)

In the above code we are importing createNetworkInterface, ApolloClient function and ApolloProvider component from react-apollo package. Now, we need to supply an endpoint to createNetworkInterface to establish connection with GraphCool back-end for making queries. Fire the command below to get the api endpoint :

graphcool endpoints

With the above command you will get three api endpoints from which we only need ‘Simple API’ and add it to the createNetworkInterface function. After that we are instantiating ApolloClient and getting the client constant which we are injecting to ApolloProvider component. Now, which ever component in which we want to use GraphQL need to be wrapped withing ApolloProvider component.

The above code will remain same for almost all the GraphQL App we will do. ( So, more than understanding you need to by-heart it 😉 )

Step 9. Create a component directory in the app directory and create a Createuser.js file in the component directory. Now, add the code below to the Createuser.js file :

import React, { Component } from 'react';
import {
  AppRegistry,
  StyleSheet,
  Text,
  View,
  TextInput,
  Button,
  ActivityIndicator
} from 'react-native';
import { graphql, gql } from 'react-apollo'
class Createuser extends Component {
  constructor(props) {
    super(props)
    this.state = {
      firstName: '',
      lastName: '',
      isLoading: false
   }
  }
  createUser = async () => {
  this.setState({ isLoading: true})
  const { firstName, lastName } = this.state
  let ret = await this.props.createUserMutation({
    variables: {
      firstName,
      lastName
    }
  })
  this.setState({ isLoading: false, firstName: '', lastName: ''})
}
  render() {
    return (
      <View style={styles.container}>
      <Text style={styles.welcome}>
        Welcome to GraphQL!
      </Text>

      <Text style={styles.label}>
        Enter first name
      </Text>
      <TextInput
        style={{height: 40,width: 200, borderColor: 'gray', borderWidth: 1, borderRadius: 10, margin: 10, alignSelf: "center"}}
        underlineColorAndroid={"transparent"}
        onChangeText={(firstName) => this.setState({firstName})}
        value={this.state.firstName}
      />
      <Text style={styles.label}>
        Enter last name
      </Text>
      <TextInput
        style={{height: 40,width: 200, borderColor: 'gray', borderWidth: 1, borderRadius: 10, margin: 10, alignSelf: "center"}}
        underlineColorAndroid={"transparent"}
        onChangeText={(lastName) => this.setState({lastName})}
        value={this.state.lastName}
      />
      { this.state.isLoading ? ( <ActivityIndicator styleAttr='Large'/> ) : (<Button
        onPress={() => this.createUser()}
        title="Create User"
        color="#841584"
      />)}

      </View>
    );
  }
}

const styles = StyleSheet.create({
  container: {
    flex: 1,
    justifyContent: 'center',
    alignItems: 'center',
    backgroundColor: '#F5FCFF',
  },
  welcome: {
    fontSize: 20,
    textAlign: 'center',
    margin: 10,
  },
  label: {
    textAlign: 'center',
    color: '#333333',
    marginBottom: 5,
  },
});

const CREATE_USER_MUTATION = gql`
  mutation CreateUserMutation($firstName: String, $lastName: String) {
    createUser(firstName: $firstName,lastName: $lastName) {
      id
      createdAt
      firstName
      lastName
    }
  }
`

export default graphql(CREATE_USER_MUTATION, { name: 'createUserMutation' })(Createuser)

In the above code, we have created a mutation at line no 87 and assigned it to constant CREATE_USER_MUTATION. Mutations are a way to write data to back-end in GraphQL.  Above mutation syntax look like 2 nested functions, where the inner function name follows a naming convention ie prefix ‘create’ followed by Schema name User. The outer function just following the ‘mutation’ keyword is the operation name. You are flexible to use any operation name. Our mutation takes two arguments ‘firstName’ and ‘lastName’. After that, we are combining the mutation with ‘Createuser’ component using ‘graphql’ container. (This looks very similar to combine of Redux. ) After combining the mutation we can use it as a prop, the way we are doing at line no. 24.

Step 10. Create a new file Listuser.js in component directory and add the code below :

import React, { Component } from 'react';
import {
  AppRegistry,
  StyleSheet,
  Text,
  View,
  ListView,
  ActivityIndicator
} from 'react-native';
import { graphql, gql } from 'react-apollo'
class Listuser extends Component {

  renderLoading(){
    return(  <View style={styles.container}>
        <ActivityIndicator styleAttr='Large'/>
      </View>)
  }
  renderError(){
    return(  <View style={styles.container}>
                <Text style={styles.welcome}>
                  An error occured
                </Text>
      </View>)
  }
  renderList(dataArray){

    return(  <View style={styles.container}>
        {
              dataArray.map(row => (
                <Text key={row.id} style={styles.instructions}>{ row.firstName} {row.lastName}</Text>
              ))
        }
      </View>)
  }

  render() {

    if(this.props.allUsersQuery && this.props.allUsersQuery.loading) {
      return this.renderLoading()
    }else if(this.props.allUsersQuery && this.props.allUsersQuery.error) {
      return this.renderError()
    }else{
    const userList = this.props.allUsersQuery.allUsers
    return this.renderList(userList)
   }
  }
}

const styles = StyleSheet.create({
  container: {
    flex: 1,
    justifyContent: 'center',
    alignItems: 'center',
    backgroundColor: '#F5FCFF',
  },
  welcome: {
    fontSize: 20,
    textAlign: 'center',
    margin: 10,
  },
  instructions: {
    textAlign: 'center',
    color: '#333333',
    marginBottom: 5,
  },
});


const ALL_USERS_QUERY = gql`
  query AllUsersQuery {
    allUsers {
      id
      createdAt
      firstName
      lastName
    }
  }
`
export default graphql(ALL_USERS_QUERY, { name: 'allUsersQuery' }) (Listuser)

In the above code we have written a query at line 69 to retrieve data from back-end. Query is similar to mutation in syntax. But, main difference that query has is the key-work query. It is used to fetch data.  Also the name convention of inner function is different i.e. prefix ‘all’ followed by schema name.

Step 11. Now to make the above app work we just need to add the code below to index.android.js/index.ios.js :

import { AppRegistry } from 'react-native'
import App from './app/App'

AppRegistry.registerComponent('ReacGraphQLApp', () => () => App)

Now, when you run your app you will get interface to add firstname and lastname. Add name of some of your friends and relatives. Then replace the line no 3 and 10 of App.js like the code below :

import React from 'react'
import { ApolloProvider, createNetworkInterface, ApolloClient } from 'react-apollo'
import Listuser from './components/Listuser'

const networkInterface = createNetworkInterface({ uri: 'https://api.graph.cool/simple/v1/cj8h0xusx000p01288nf9eemh' })
const client = new ApolloClient({ networkInterface })

export default (
  <ApolloProvider client={client}>
    <Listuser />
  </ApolloProvider>
)

Now, reload app and you will get to see the names of friends and relatives you added using ‘Createuser’ component.

This was just the first step of journey of thousand miles of world of GraphQL. We will keep doing some interesting stuffs and honing our GraphQL skills. Stay tuned to everything we do by subscribing you our news letter and subscribing to our Youtube channel.

Video Tutorial

 

2 thoughts on “Getting started with React Native and GraphQL Step by Step”

Comments are closed.