Serverless mobile application development made with React Native and AWS MobileHub

What is AWS MobileHub

AWS MobileHub is a service of AWS that can manage the construction and processing of the back end side of the application at once and can make it fast and simple. In S3, you can manage AWS services that are frequently used in mobile applications such as data storage, data management with dynamoDB and API Gateway, user login on Facebook, and so on.

Please check the official website here for more details.

Things to be shared

Using MobileHub,

  • How to save data in dynamoDB
  • How to upload images to S3

Preparation

  • React Native Developing Environment
  • AWS account

Steps

1. Create React Native app

Create an application following Getting Started from React Native

2. Setup AWS MobileHub

  1. Access to AWS MobileHub

  2. Create Your Projects

  3. Enter project name at Create a project

  4. Select application at Select app platform

    Select React Native and check on Enable web hosting with your app

  5. Execute the following at terminal depends on Set up your backend

# install awsmobile-cli
npm install -g awsmobile-cli

# setup with awsmobile command
cd (my-awesome-app)/client
awsmobile init (your-app-code)
 # Interactive input. The source directory is input according to the environment, otherwise basic defaults is also OK
  1. Done at Connect to your backend

When setting up with only awsmobile command You can also set up by command only with reference to AWS official here

  • If AMI user creation has not been done yet we have to create it first like this
awsmobile configure
# input interactive Access Key ID and Secret Access Key

3. Create Database

  1. Select NoSQL Database in target project of AWS MobileHub
  2. Create table with Add Table Here we create a Notes table

Items

  • NoteId: string
  • NoteTitle: string
  • NoteContent: string
  1. Run awsmobile pull to run it locally

4. Create CRUD API

Create API, register at the table that we created in 3. Is CRUD API currently not created from AWS MobileHub? Therefore, we create from the terminal and push it.

awsmobile cloud-api enable --prompt
 # settings as interactive
 # Choose the below
 > Create CRUD API for an existing Amazon DynamoDB table 

 # point to the table created at 5.
 > Notes


# push setting of API
awsmobile push

When creating the second or later CRUD API, execute the following command

awsmobile cloud-api configure

5. Install important package

npm install aws-amplify --save
npm install aws-amplify-react-native --save
react-native link

6. Change the source code

import Amplify, { API } from 'aws-amplify-react-native';
import { awsmobile } from './aws-exports'; // point the path aws-exports.js

Amplify.configure(awsmobile);

Code to register practically

async saveNote() {
  const newNote = {
    body: {
      NoteId: 'id001',
      NoteTitle: 'My first note!',
      NoteContent: 'This is so cool!'
    }
  }
  const path = "/Notes";

  // Use the API module to save the note to the database
  try {
    const apiResponse = await API.put("NotesCRUD", path, newNote)
    console.log("response from saving note: " + apiResponse);
  } catch (e) {
    console.log(e);
  }
}

Run the below code at the place you want to register

this.saveNote();

7. Firstly Run it

react-native run-ios
# or
react-native run-android

if you run with iOS, use Xcode to run it

Steps to upload images

8. Enable Storage of AWS S3

  1. Select User Data Storage in the target project of AWS MobileHub
  2. Select Store user data
  3. Save changes
  4. Run awsmobile pull and enable it locally

This creates a bucket for Storage in S3.

9. Install important package

react-native-image-picker

react-native-fetch-blob

npm install react-native-fetch-blob --save
npm install [email protected] --save
npm install buffer
react-native link

10. Create files.js

Create files.js and add the below code

import { Buffer } from 'buffer';
import RNFetchBlob from 'react-native-fetch-blob';

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

11. Add source code

Add import

import Amplify, { API, Storage } from 'aws-amplify-react-native';
import RNFetchBlob from 'react-native-fetch-blob';
import ImagePicker from 'react-native-image-picker';

import { awsmobile } from './aws-exports'; // point path of aws-exports.js
import files from './files'; // point path of files.js

Amplify.configure(awsmobile);

Uploading source code

saveImage = () => {
  const options = {
    title: 'Select Avatar',
    storageOptions: {
      skipBackup: true,
      path: 'images'
    }
  };

  ImagePicker.showImagePicker(options, (response) => {
    console.log('Response = ', response);

    if (response.didCancel) {
      console.log('User cancelled image picker');
    }
    else if (response.error) {
      console.log('ImagePicker Error: ', response.error);
    }
    else if (response.customButton) {
      console.log('User tapped custom button: ', response.customButton);
    }
    else {
      RNFetchBlob
      .config({
        fileCache: true,
        appendExt: 'png',
      })
      .fetch('GET', response.uri, {
      })
      .then((res) => {
        // upload to storage
        files.readFile(res.data)
          .then(buffer => Storage.put('image.png', buffer, { level: 'public', contentType: 'image/png' }))
          .then(x => console.log('SAVED', x) || x);
      });
    }
  });
}

Run the code below where you want to upload

this.saveImage();

Display the uploaded image

// Add S3Image
import Amplify, { API, Storage, S3Image } from 'aws-amplify-react-native';

// ~ ... ~

// Display
<S3Image imgKey={'image.png'} />

12. Execute

react-native run-ios
# or
react-native run-android

If you run with iOS, use Xcode to run it


All Rights Reserved