Skip to main content

Building Serverless Mobile Applications with React Native & AWS

Building Server-less Mobile Applications with React Native & AWS

When building a real-world mobile application there are a ton of essential basic requirements.

You need to have a way to authenticate users, you want to track user engagement & usage, & you probably want to be able to send push notifications and maybe base these messages on events or user behavior. Then you have to manage your application data and are probably dealing with multiple REST endpoints. You’re also usually dealing with media such as images & videos and you hopefully want to be able to handle offline use cases so that the app continues to work whether or not they are online.

Getting Started

Creating the React Native App

First we’ll create a new React Native project using either the React Native CLI or the Create React Native App CLI:

react-native init ServerlessProject
cd ServerlessProject

Installing the AWS Mobile CLI

The AWS Mobile CLI offers a way to quickly & easily spin up new AWS Mobile Hub projects from the command line.

npm i -g awsmobile-cli
awsmobile configure
awsmobile init
react-native link amazon-cognito-identity-js

Configuring the React Native app with your new AWS Mobile Hub project.

Now that the Mobile Hub project has been created & the dependencies are all installed, we can configure the React Native project to recognize our configuration.

import { AppRegistry } from 'react-native';
import App from './App';
import Amplify from 'aws-amplify' // NEW
import config from './aws-exports' // NEW
Amplify.configure(config
) // NEW
AppRegistry.registerComponent('ServerlessProject', () => App);

User Sign Up & Sign In

The first thing we’ll do is look at how we can add user sign up & sign in.

awsmobile user-signin enableawsmobile push
  1. We can use the React components & higher order components for preconfigured functionality & UI
  2. We can write this functionality from scratch using the Auth class which contains methods like Auth.signUp() & Auth.signIn()

React Native Components

Let’s first check out how to use the withAuthenticator HOC from aws-amplify-react-native.

import { withAuthenticator } from 'aws-amplify-react-native'
class App extends Component {
// all of this code stays the same
}
export default withAuthenticator(App)
react-native run-ios
// or
react-native run-android
<Authenticator>
<App />
</Authenticator>

Auth Class

We can also use the Auth class to authenticate users.

import { Auth } from 'aws-amplify'// in your component
Auth.signIn('myusername', 'mYC0MP13xP@55w0r8')
import { Auth } from 'aws-amplify'

class App extends React.Component {
  state = {
    username: '',
    password: '',
    phone_number: '',
    email: '',
    authCode: '',
    user: {}
  }
  async signUp() {
    const { username, password, email, phone_number } = this.state
    await Auth.signUp({
      username,
      password,
      attributes: { email, phone_number }
    })
    console.log('sign up successful!')
  }
  async confirmSignUp() {
    const { username, authCode } = this.state
    await Auth.configSignignUp(username, authCode)
    console.log('confirm sign up successful!')
  }
  async signIn() {
    const { username, password  } = this.state
    const user = await Auth.signIn(username, password)
    this.setState({ user })
    console.log('sign in successful!')
  }
  async confirmSignIn() {
    const { user, authCode } = this.state
    await Auth.configSignignIn(user, authCode)
    console.log('user now successfully signed in to the app!!')
  }
  render() {
    // render method
  }
}
awsmobile console
AWS Mobile Hub project showing enabled services
Links to all enabled resources

Analytics

Analytics events can be tracked using the Analytics class.

Analytics.record('sale price section viewed')
Analytics.record('sale price item viewed', { itemName: 'USA Socks' , timestamp: 'June 13 2018 4:03pm ET' })
awsmobile console
// Click on Resources, then Pinpoint
Pinpoint dashboard

Storage

Amplify has a Storage class that allows easy interop with React Native making the storage and access of media like images & media much easier, working seamlessly with Amazon S3.

awsmobile user-files enable
awsmobile push
import { Storage } from 'aws-amplify'
Storage.put('test.txt', 'Hello')
.then (result => console.log(result))
.catch(err => console.log(err));
Storage.get('test.txt')
.then(result => console.log(result))
.catch(err => console.log(err));
import RNFetchBlob from 'react-native-fetch-blob';

readFile(filePath) {
return RNFetchBlob.fs.readFile(filePath, 'base64').then(data => new Buffer(data, 'base64'));
}

readFile(imagePath).then(buffer => {
Storage.put('MYKEY', buffer, {
contentType: 'image/jpeg'
})
}).catch(e => {
console.log(e);
});

Lambda Functions

When you hear “Serverless” you may typically think of a Lambda function. We can set one of these up manually and connect it with our existing AWS Amplify resources, or we can use the AWS Mobile CLI to set this up for us. Let’s continue using the CLI to create the new Lambda function.

awsmobile cloud-api enable
/// rest of file omittedapp.get('/items', function(req, res) {
res.json({
body: "HELLO WORLD"
});
});
awsmobile push
awsmobile console
async componentDidMount() {
const data = await API.get('sampleCloudApi', '/items')
console.log('data: ', data)
}

Managed API & Data Layer

type Todo {
id: ID!
name: String!
completed: Boolean!
}
type Query {
fetchTodos(id: ID!): Todo
}
mutation add {
createTodo(input: {
name: "Get groceries"
completed: false
}) { id }
}
query list {
listTodos {
items {
id
name
completed
}
}
}
export default {
  'aws_appsync_graphqlEndpoint': 'https://*******.appsync-api.us-east-1.amazonaws.com/graphql',
  'aws_appsync_region': 'us-east-1',
  'aws_appsync_authenticationType': 'API_KEY',
  'aws_appsync_apiKey': 'da2-*************',
}
import { AppRegistry } from 'react-native';
import App from './App';
import Amplify from 'aws-amplify'
import config from './aws-exports'
import AppSyncConfig from './appsync-config' // NEW
Amplify.configure({ ...config, ...AppSyncConfig }
) // UPDATED
AppRegistry.registerComponent('ServerlessProject', () => App);
import React, { Component } from 'react';
import {
  StyleSheet,
  Text,
  View
} from 'react-native';

import { withAuthenticator } from 'aws-amplify-react-native'
import { API, graphqlOperation } from 'aws-amplify'

const query = `
  query list {
    listTodos {
      items {
        id
        name
        completed
      }
    }
  }
`

class App extends Component {
  state = { todos: [] }
  async componentDidMount() {
    const todos = await API.graphql(graphqlOperation(query))
    this.setState({ todos: todos.data.listTodos.items })
  }
  render() {
    return (
        <View style={styles.container}>
          <Text style={styles.welcome}>
            Todos
          </Text>
          {
            this.state.todos.map((todo, index) => (
              <Text key={index}>{todo.name}</Text>
            ))
          }
        </View>
    );
  }
}

export default withAuthenticator(App)

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

Push Notifications are available for both Android & iOS in AWS Amplify.

import { PushNotification } from 'aws-amplify-react-native';

// get the registration token
PushNotification.onRegister((token) => {
  console.log('in app registration', token);
});

PushNotification.onNotification((notification) => {
  // Note that the notification object structure is different from Android and IOS
  console.log('in app notification', notification);

  // required on iOS only (see fetchCompletionHandler docs: https://facebook.github.io/react-native/docs/pushnotificationios.html)
  notification.finish(PushNotificationIOS.FetchResult.NoData);
});

Comments

Popular Posts

Reloading UITableView while Animating Scroll in iOS 11

Reloading UITableView while Animating Scroll Calling  reloadData  on  UITableView  may not be the most efficient way to update your cells, but sometimes it’s easier to ensure the data you are storing is in sync with what your  UITableView  is showing. In iOS 10  reloadData  could be called at any time and it would not affect the scrolling UI of  UITableView . However, in iOS 11 calling  reloadData  while your  UITableView  is animating scrolling causes the  UITableView  to stop its scroll animation and not complete. We noticed this is only true for scroll animations triggered via one of the  UITableView  methods (such as  scrollToRow(at:at:animated:) ) and not for scroll animations caused by user interaction. This can be an issue when server responses trigger a  reloadData  call since they can happen at any moment, possibly when scroll animation is occurring. Example of s...

What are the Alternatives of device UDID in iOS? - iOS7 / iOS 6 / iOS 5 – Get Device Unique Identifier UDID

Get Device Unique Identifier UDID Following code will help you to get the unique-device-identifier known as UDID. No matter what iOS user is using, you can get the UDID of the current iOS device by following code. - ( NSString *)UDID { NSString *uuidString = nil ; // get os version NSUInteger currentOSVersion = [[[[[UIDevice currentDevice ] systemVersion ] componentsSeparatedByString: @" . " ] objectAtIndex: 0 ] integerValue ]; if (currentOSVersion <= 5 ) { if ([[ NSUserDefaults standardUserDefaults ] valueForKey: @" udid " ]) { uuidString = [[ NSUserDefaults standardDefaults ] valueForKey: @" udid " ]; } else { CFUUIDRef uuidRef = CFUUIDCreate ( kCFAllocatorDefault ); uuidString = ( NSString *) CFBridgingRelease ( CFUUIDCreateString ( NULL ,uuidRef)); CFRelease (uuidRef); [[ NSUserDefaults standardUserDefaults ] setObject: uuidString ForKey: @" udid " ]; [[ NSUserDefaults standardUserDefaults ] synchro...

Xcode & Instruments: Measuring Launch time, CPU Usage, Memory Leaks, Energy Impact and Frame Rate

When you’re developing applications for modern mobile devices, it’s vital that you consider the performance footprint that it has on older devices and in less than ideal network conditions. Fortunately Apple provides several powerful tools that enable Engineers to measure, investigate and understand the different performance characteristics of an application running on an iOS device. Recently I spent some time with these tools working to better understand the performance characteristics of an eCommerce application and finding ways that we can optimise the experience for our users. We realised that applications that are increasingly performance intensive, consume excessive amounts of memory, drain battery life and feel uncomfortably slow are less likely to retain users. With the release of iOS 12.0 it’s easier than ever for users to find applications that are consuming the most of their device’s finite amount of resources. Users can now make informed decisions abou...