React Native + GraphQL -> Part 1
This article is focused to explain the basic fundamentals of using GraphQL with React Native. I’m assuming that you know a bit the React Native or React (Components, Props, State, etc). If you don’t know anything about ReactJS I first recommend to you review the concepts of it.
GraphQL?
According to the official website of GraphQL, we could defined it:
GraphQL is a query language for your API, and a server-side runtime for executing queries by using a type system you define for your data. GraphQL isn’t tied to any specific database or storage engine and is instead backed by your existing code and data.
Using GraphQL we can ask something what you need and getting exactly that. GraphQL queries always return predictable results. The apps that are using GraphQL are fast and stable because they control the data they get, not the server. GraphQL queries access not just the properties of one resource but also smoothly follow references between them. While typical REST APIs require loading from multiple URLs, GraphQL APIs get all the data your app needs in a single request. Apps using GraphQL can be quick even on slow mobile network connections.
GraphQL creates a uniform API across your entire application without being limited by a specific storage engine. Write GraphQL APIs that leverage your existing data and code with GraphQL engines available in many languages. You provide functions for each field in the type system, and GraphQL calls them with optimal concurrency.
Ok, if you are motivated to learn more about GraphQL, you can visit http://graphql.org/learn/. It’s a great documentation, you can find tutorials and examples that helping you to learn more about GraphQL.
To continue I’ll develop an Instagram app, where users can view and post images. Are you ready? Are still you motivated? I hope that you are! Let’s Go!
Getting started
You have a lot of ways to create a React Native project but I recommend to you use the create-react-native-app,
it’s super easy to start out with a new React Native application! It comes with a lot of nice features and configurations out-of-the-box, let’s you easily run your app on a real-device by scanning a QR code from the terminal and saves you from having to use native development tools such as Xcode or Android Studio.
If you don’t have installed the created-react-native-app, now is a genial time of doing it with the following command.
`npm install -g create-react-native-app`
After installing, we can easily create and run a new project from the command line:
create-react-native-app react-native-instagram-example
cd react-native-instagram-example
react-native run-ios # or
react-native run-android
The app should looks like in the IOS simulator:
Hot-reloading is already setup as well, so any changes you make in the JavaScript code will immediately appear on the screen! I love it!
Integrating Apollo in a React Native application
Apollo Client is one of the most popular GraphQL clients available at the moment. It implements features like caching, optimistic UI, query batching as well as realtime updates using subscriptions and generally makes interacting with a GraphQL backend a breeze.
You’ll need three dependencies to use it in our React application:
apollo-client
: Contains the general functionality of Apollo Clientreact-apollo
: Implements React-specific bindings for Apollographql-tag
: Provides functionality for parsing the JavaScript template literals that will contain our GraphQL queries and mutations.
You can install all three dependencies at once:
npm install apollo-client react-apollo graphql-tag --save
Additionally, we’re using React Router Native to deal with navigation in our app, let’s go ahead install that as well:
npm install react-router-native --save
Mocking the needed components
Let’s first build the components needed for our app, where we want to display, create or delete posts. Afterwards, we’ll inject the required data using Apollo and wire everything up with React Router.
Ok first that all you should create a folder called components
, where we’ll create the components that will use in the app.
These are the three main components that we’ll need:
ListPage
incomponents/ListPage.js
that will list all posts in our backend.
import React from 'react'
import { ScrollView, View, Text, Button } from 'react-native'
import { withRouter } from 'react-router-native'class ListPage extends React.Component {render () {
return (
<View>
<ScrollView>
<View
style={
{
flex: 1,
flexDirection: 'column',
justifyContent: 'center',
alignItems: 'center',
}
}
>
// here is where we will render our posts
</View>
</ScrollView>
<Button
onPress={this.createPost}
title="Create Post"
/>
</View>
)
}createPost = () => {
this.props.router.push('/create');
}
}
CreatePage
incomponents/CreatePage.js
to create new posts
import React from 'react'
import { View, TextInput, Button, Image, Text } from 'react-native'
import { withRouter } from 'react-router-native'class CreatePage extends React.Component {state = {
description: '',
imageUrl: '',
}render () {return (
<View>
<TextInput
style={{height: 40, borderColor: 'gray', borderWidth: 1}}
onChangeText={(text) => this.setState({description: text})}
placeholder={'Description'}
/>
<TextInput
style={{height: 40, borderColor: 'gray', borderWidth: 1}}
onChangeText={(text) => this.setState({imageUrl: text})}
placeholder={'Image Url'}
/>
{this.renderImage()}
{this.renderButton()}
</View>
)
}renderButton() {
if (this.state.description && this.state.imageUrl) {
return (
<Button title={'Post'} onPress={this.handlePost} />
)
}
return null
}renderImage() {
if (this.state.imageUrl) {
return (
<Image
source={{ uri: this.state.imageUrl }}
style={{width: 200, height: 200}}
/>
)
}
return null
}handlePost = () => {
// we'll learn what to do here in a bit :)
}
}
Post
incomponens/Post.js
to display and delete a single post
import React from 'react'
import { View, Image, Text } from 'react-native'export default class Post extends React.Component {static propTypes = {
post: React.PropTypes.object,
}render () {
return (
<View style={{flex: 1, width: 150, height: 150}}>
<Image
source={{ uri: this.props.post.imageUrl }}
style={{flex: 1, width: 150, height: 150}}
/>
<Text>{this.props.post.description}</Text>
</View>
)
}
}
So far, we’ve created a React Native project with 3 components. In the second part, we’ll integrate it with Apollo and GraphQL. See you soon, thanks for reading.